web-dev-qa-db-ja.com

Eloquent Ormで自己参照(parent_id)モデルを実装する方法

Userテーブルがあり、ユーザーが親ユーザーを持つことを許可する必要があります。

テーブルには次のフィールドがあります。

  • id
  • parent_id
  • email
  • password

Eloquent ORMでこの自己参照関係をどのように定義しますか?

19

正確な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();

それを試してみて、あなたがどのように乗るかを私に知らせてください!

39
msturdy

自己参照契約のチェーンがあり(契約は別の契約で継続できます)、自己参照も必要でした。各契約には、前の契約が0または1つあり、次の契約も0または1つあります。

私のデータテーブルは次のようになりました。

+------------------+  
| 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-to-one を参照してください。