laravel - 如何在 Laravel 迁移和模型中建立自反关系

标签 laravel laravel-5 eloquent

我想要一个,它本身有一个一对多。例如:我有一个 people 表,它可以有许多其他 people。这就是我的代码的样子:

public function up()
{
    Schema::create('people', function (Blueprint $table) {
        $table->string('id')->primary();//Here my PK is a string
        $table->string('name');
        $table->string('title')->nullable();
        $table->string('parent_id');//Here is the foreign key of another person
        $table->timestamps();
    });
}

在我的 Person.php 模型中我有这个:

public function people()
{
    return $this->belongsTo('App\Person')->withDefault();
}

public function person()
{
    return $this->hasMany('App\Person');
}

看看这张图片:

The relashionship that i'm trying to implement

最佳答案

Person.php 模型中:

public function parent()
{
    return $this->belongsTo('App\Person', 'parent_id');
}

public function child()
{
    return $this->hasMany('App\Person', 'parent_id');
}

关于laravel - 如何在 Laravel 迁移和模型中建立自反关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139867/

相关文章:

Laravel:使用自动填充 created_at 和 updated_at 插入多条记录

php - Laravel 5.1 任务调度命令问题

php - 使用 Relation Laravel 5.1 创建记录

mysql - 如何使用 Eloquent 获取 N 个最新的数据库条目?

php - 如何在 Laravel 中将 INFO 记录到单独的文件中

php - Eloquent:如何在 withDefault() 闭包中访问相关模型?

mysql - Laravel 表拒绝在迁移表上注册并回滚或迁移

laravel - 使用 laravel-mix 编译 ES6 React 代码

javascript - laravel中使用ajax jquery将数据添加到数据库

Laravel - 调用未定义的方法illuminate\Foundation\Application::bindshared()