dongyixiu3110
2015-12-28 21:32
浏览 62
已采纳

Laravel Eloquent - >只获得城市所在的活动

I have a table with:

Events
Cities
Clubs

The relations are as following:

  • An Event 'hasOne' Club, and a Club 'hasMany' Events.
  • A Club 'hasOne' City and a City 'hasMany' Clubs.

I want to add a filter to my query to get all events where the club.city == 'Oklahoma'. This is what I tried:

$events = Event::where( 'accepted', 1 )
                ->with( [ 'club.city', 'organisation' ] )
                ->where( 'club.city.name', 'Rotterdam' )
                ->orderBy( 'created_at', 'asc' )
                ->paginate( 6 );
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushitang4276 2015-12-29 03:01
    已采纳

    You can use whereHas to filter based on existance of a condition on a relationship.

    $events = Event::where( 'accepted', 1 )
        ->with( [ 'club.city', 'organisation' ] )
        ->whereHas('club.city', function ($q) use ($cityname) {
            $query->where('name', $cityname);
        })->orderBy( 'created_at', 'asc' )
        ->paginate( 6 );
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题