Laravel 5.5 模型关联问题,请问大家,模型怎么和自己关联呢?

Laravel 5.5 模型关联问题,请问大家,模型怎么和自己关联呢?
请大家指点一下!!!非常感谢

我尝试了

public function simulation_parent()
    {
        return $this->belongsTo(Simulation::class,'template_id');
    }

public function simulation_child()
    {
        return $this->hasMany(Simulation::class);
    }

但是无效。。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

就是你这样关联的 当然有效

建议装个Laravel Debugbar 来查看sql

3年前 评论
HEPING (楼主) 3年前
讨论数量: 2

是这个意思么

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('pid')->default(0);
            $table->integer('type')->default(1);
            $table->integer('sort')->default(0);
            $table->tinyInteger('show_in_menu')->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Category extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'pid',
        'name',
        'sort',
        'type',
        'show_in_menu'
    ];

    public function childCategory()
    {
        return $this->hasMany('App\Models\Category', 'pid', 'id');
    }

    public function allChildrenCategories()
    {
        return $this->childCategory()->with('allChildrenCategories');
    }

    /**
     * 无限递归处理分类信息,输出一个一维集合
     *
     * @param Collection $category
     * @param int $pid
     * @param int $level
     *
     * @return array|Collection|static
     */
    public function getCategoryLevel(Collection $category, $pid = 0, $level = 0)
    {
        ++$level;
        $sub = new Collection();
        foreach ($category as $value) {
            if ($value->pid == $pid) {
                $value->level = $level;
                $sub[] = $value;
                $sub = $sub->merge($this->getCategoryLevel($value->allChildrenCategories, $value->id, $level));
            }
        }

        return $sub;
    }
}
3年前 评论
HEPING (楼主) 3年前

就是你这样关联的 当然有效

建议装个Laravel Debugbar 来查看sql

3年前 评论
HEPING (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!