假設有三張Table要查詢:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
countries id <span class="token operator">-</span> integer name <span class="token operator">-</span> string users id <span class="token operator">-</span> integer country_id <span class="token operator">-</span> integer name <span class="token operator">-</span> string posts id <span class="token operator">-</span> integer user_id <span class="token operator">-</span> integer title <span class="token operator">-</span> string |
類似中文官方文件中的「遠層一對多關聯」,第一種寫法就是官方建議的,雖然 posts
資料表本身沒有 country_id
欄位,但 hasManyThrough
方法讓我們可以使用$country->posts
取得 country 的 posts。我們可以定義以下關聯:
1 2 3 4 5 6 7 8 |
class Country extends Eloquent { public function posts() { return $this->hasManyThrough('Post', 'User'); } } |
如果想要手動指定關聯的欄位名稱,可以傳入第三和第四個參數到方法裡:
1 2 3 4 5 6 7 8 |
class Country extends Eloquent { public function posts() { return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id'); } } |
第二種方法則可以使用巢狀查詢:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Country extends Eloquent { public function user() { return $this->has_many( 'Users' ); } } class Users extends Eloquent { public function post() { return $this->has_many( 'Post' ); } } class Post extends Eloquent {} $country = Country ::with( array( 'user', 'user.post' ) )->first(); |