更好的嵌套查询方法

时间:2016-07-17 09:07:27

标签: laravel-5 laravel-query-builder

我在Laravel非常新。

我有这个查询

$city = City::where('slug', $slug)->first();
$city->users = $city->users()->where('gender', 'male')->get();

所以我想知道对于这种情况有什么更好的方法。总而言之,我需要找到一个城市以及属于城市性别=男性的所有用户。

我试图这样做但是没有用

$city = City::whereHas('users', function($q) {
            $q->where('gender', '=', 'male');
        })->where('slug', $slug)
          ->first();

我缺少什么?

1 个答案:

答案 0 :(得分:1)

我相信Laravel的Eager Loading是可能的。 您可以在城市模型类中正确设置关系

$city = City::where('slug', $slug)
        ->with(['users' => function ($query) {
                               $query->where('gender', 'male');
                           }])->first();