0

我是 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();

我错过了什么?

4

1 回答 1

1

我相信这可以通过 Laravel 的Eager Loading实现。在您的 City 模型类中正确设置关系后,您可以这样做

$city = City::where('slug', $slug)
        ->with(['users' => function ($query) {
                               $query->where('gender', 'male');
                           }])->first();
于 2016-07-17T09:17:23.863 回答