首页 > 解决方案 > 如何在 laravel 中创建父/子关系?

问题描述

我在 laravel 6.0.4 中有这个模型:

class CategoryModel extends Model
{
    public function parent()
    {
        return $this->belongsTo(CategoryModel::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(CategoryModel::class, 'parent_id');
    }
}

和控制器

class CategoryController extends Controller
{
    public function index()
    {
        CategoryModel::with('children')->get(); // this is working
        CategoryModel::with('parent')->get(); // this is not working
    }
}

这是架构

Schema::create('category', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('parent_id')->nullable();
    $table->string('name');

    $table->index(['parent_id']);
    $table
        ->foreign('parent_id')
        ->references('id')
        ->on('category')
        ->onDelete('set null')
        ->onUpdate('set null');
});

我可以得到孩子,但对于父母,它为所有记录返回一个空数组。

标签: phplaravel

解决方案


试试这个:

public function parent()
{
    return $this->hasOne(CategoryModel::class, 'id', 'parent_id');
}

public function children()
{
    return $this->hasMany(CategoryModel::class, 'parent_id', 'id');
}

推荐阅读