2015-12-17 28 views
0
User::with(array('post'=>function($query){ 
    $query->select('id','user_id'); 
}))->get();  

它將如何成爲多個連接的語法?我需要用3個連接和1個條件來做到這一點。如何使用雄辯進行多個連接?

+1

護理來發表您的模型?你檢索單個* join *的方式很好 - 你應該從它開始。 ':: with($ parameter)'方法接受數組(和字符串)參數,所以你可以做'User :: with(array('post'=> ...,'rel2'=> ...., ''rel3'=> .....,.....) - > where('someField','someValue') - > get()'should work。[api](http:// laravel .com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_with)和[source](https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model。 php#L731),並且不要忘記* dot *用於嵌套關係的魔力 –

+0

你這樣做的方式 - 在SQL級別上不會有任何連接,將會有2個SQL查詢運行 - 一個可以獲取用戶和用戶加載他們的帖子 –

+0

你應該使用'whereHas()',或者只是'has()'more info [here。](http://laravel.com/docs/5.1/eloquent-relationships#查詢關係)但是,你也可以保持基礎,並使用簡單的'join()'[here。](http://laravel.com/docs/5.1/queries#joins)它實際上取決於你的偏好至 使用。 – Joost

回答

0

嘗試類似的東西在你的用戶模型:

public static function wherePost(\App\Post $post) { 

    return static::leftJoin(
     'posts', 
     'user.id', '=', 'posts.user_id' 
    ) 
    // ... more joins 
    ->where('posts.id', $post->id) 
    ->select(with(new static)->getTable().'.*'); 
} 

比你可以從一個特定的帖子一樣,獲得用戶: $user = User::wherePost($post);