我有这个选择,但是我不知道如何仅获取事件不为空的寄存器:
$getUsers = User::where('user_id', $userId)
->with(['events' => function($query) {
$query->where('finnish', 0)
->orderBy('event_id', 'desc');
}])
->get();
通过此查询,我得到以下结果,其中用户未满足关系的where条件:
{
"events": [
{
"user_id": 1,
"event_id": 1,
"created_at": null,
"updated_at": null,
"events": {
"event_id": 1,
"name": "test 1"
}
},
{
"user_id": 1,
"event_id": 25,
"created_at": null,
"updated_at": null,
"events": null
},
{
"user_id": 1,
"event_id": 34,
"created_at": null,
"updated_at": null,
"events": null
}
]
}
我只喜欢这样:
{
"events": [
{
"user_id": 1,
"event_id": 1,
"created_at": null,
"updated_at": null,
"events": {
"event_id": 1,
"name": "test 1"
}
]
}
谢谢
答案 0 :(得分:4)
您可以使用->has('events')
查询relationship existence。
如果您想要额外的过滤器,可以使用whereHas
。
$getUsers = User::where('user_id', $userId)
->whereHas('events', function function($query) {
$query->where('finnish', 0);
}
->with(['events' => function($query) {
$query->where('finnish', 0)
->orderBy('event_id', 'desc');
}])
->get();