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);
    }

但是无效。。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

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

建议装个Laravel Debugbar 来查看sql

4年前 评论
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;
    }
}
4年前 评论
HEPING (楼主) 3年前

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

建议装个Laravel Debugbar 来查看sql

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

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