2013-07-20 59 views
5

我想使用自定義數據庫結構來構建Laravel應用程序。我有表types,units,content和一個稱爲relations的數據透視表。在relations表的結構是這樣的:雄辯ORM/Laravel - 使用自定義數據透視表結構

--------------------------------------------- 
| id | relation_type | first_id | second_id | 
--------------------------------------------- 
| 1 | type_unit |  1 | 2  | 
--------------------------------------------- 
| 2 | unit_content |  2 | 3  | 
--------------------------------------------- 

換句話說,前三個表有許多到許多關係本身之中,而第四個是所有關係中的數據透視表。我該如何使用這個數據透視表結構的Eloquent's BelongsToMany方法,即如何只選擇與給定關係相關的數據透視表記錄?例如,我怎麼會只用type_unit關係,在此:

class Type extends Eloquent { 

    public function units() 
    { 
     return $this->belongsToMany('Unit', 'relations'); 
    } 

} 

,但同時忽略unit_content關係?

回答

12

belongsToMany會接受第3和第4個參數。你可以看到它在文檔:http://laravel.com/docs/eloquent#relationships

但是,這不是在文檔中的事情是,你可以通過鏈接查詢生成器功能,如where,約束你們的關係orderBy

所以,你的代碼會是這樣的:

class Type extends Eloquent { 

    public function units() 
    { 
     return $this->belongsToMany('Unit', 'relations', 'first_id', 'second_id') 
      ->withPivot(['relation_type']) 
      ->where('relations.relation_type', '=', 'type_unit'); 
    } 

} 
+0

Umut你是明星,謝謝! –

+0

很高興我能幫到你。 :) –

相關問題