在Laravels Eloquent中,我如何获得关系记录?

Laz*_*tle 2 php laravel eloquent laravel-5

我试图拉出所有事件关系的记录,事件日期为今天.我有以下代码:

    EventStaffStation::with([
        'event' => function($query) {
            $query->where('event_date', Carbon::now()->format('d-m-Y'));
        }
    ])->where([
        'staff_id' => auth()->user()->id
    ])->has('event')->get()
Run Code Online (Sandbox Code Playgroud)

这给了我一个记录event_staff_stations但它将事件关系设置为null.如果关系为null,我希望不返回记录.

基本上如果event_staff_station记录不适合今天,那么我不希望它返回.我只对今天活动日的记录感兴趣.

任何帮助表示赞赏.

Mar*_*łek 6

你应该使用:

EventStaffStation::whereHas(
    'event' , function($query) {
        $query->where('event_date', Carbon::now()->format('d-m-Y'));
    }
)->where([
    'staff_id' => auth()->user()->id
])->get()
Run Code Online (Sandbox Code Playgroud)

如果你想根据关系存在/条件获得记录,你应该使用has/whereHas而不是with.当然,在上面的查询中,您还可以添加with,如果需要,将急切加载您想要的任何关系.