如何在Eloquent Orm中实现自引用(parent_id)模型


How to implement a self referencing (parent_id) model in Eloquent Orm

我有一个User表,需要允许用户有一个父用户。

该表将包含以下字段:

  • id
  • parent_id
  • email
  • password

在Eloquent ORM中,我将如何定义这种自我参照关系?

我使用了您的精确DB表,在这方面取得了一些成功。

用户模型

class User extends Eloquent {
    protected $table = 'users';
    public $timestamps = false;
    public function parent()
    {
        return $this->belongsTo('User', 'parent_id');
    }
    public function children()
    {
        return $this->hasMany('User', 'parent_id');
    }
}

然后我可以在我的代码中使用它,如下所示:

$user     = User::find($id);
$parent   = $user->parent()->first();
$children = $user->children()->get();

试试看,让我知道你进展如何!

我有一系列自引用合同(一个合同可以由另一个合同继续),也需要自引用。每个合同都有零个或一个以前的合同,也有零个或者一个下一个合同。

我的数据表如下所示:

+------------------+  
| contracts        |  
+------------------+  
| id               |  
| next_contract_id |  
+------------------+  

要定义关系(上一个合同)的反转,必须反转相关列,这意味着设置*模型表上的外键列*父表(同一个表)上的关联列

<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class Contract extends Model {
    // The contract this contract followed
    function previousContract()
    {
        // switching id and next_contract_id
        return $this->belongsTo('App'Contract', 'id', 'next_contract_id');
    }
    // The contract that followed this contract
    function nextContract()
    {
        return $this->belongsTo('App'Contract');
        // this is the same as
        // return $this->belongsTo('App'Contract', 'next_contract_id', 'id');
    }
}

请参阅http://laravel.com/docs/5.0/eloquent#one-到一个了解更多细节。