Laravel where on relationship object

那年仲夏 提交于 2019-12-02 20:00:18

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

Hamid Naghipour

@Cermbo's answer is not related to this question. in this answer, Laravel will give you all Events if per Event has 'participants' with IdUser is 1.

But if you want to get all Events with all 'participants' provided that per 'partecipants' with IdUser is 1, then you should do something like this :

Event::with(["participants" => function($q){
    $q->where('participants.IdUser', '=', 1);
}])

attention to:

in where use your table name, no Model name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!