我正在使用Laravel 5.0开发一个Web API,但我不确定我正在尝试构建的特定查询。
我的课程如下:
class Event extends Model {
protected $table = 'events';
public $timestamps = false;
public function partecipants()
{
return $this->hasMany('App\Partecipant', 'IDEvent', 'ID');
}
public function owner()
{
return $this->hasOne('App\User', 'ID', 'IDOwner');
}
}
和
class Partecipant extends Model {
protected $table = 'partecipants';
public $timestamps = false;
public function user()
{
return $this->belongTo('App\User', 'IDUser', 'ID');
}
public function event()
{
return $this->belongTo('App\Event', 'IDEvent', 'ID');
}
}
现在,我希望与特定参与者一起获得所有活动。我尝试过:
Event::with('partecipants')->where('IDUser', 1)->get();
但where
条件适用于Event
而不是Partecipants
。以下是一个例外:
Partecipant::where('IDUser', 1)->event()->get();
我知道我可以这样写:
$list = Partecipant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
但是向服务器发送这么多查询似乎并不高效。
使用Laravel 5和Eloquent通过模型关系执行where
的最佳方法是什么?
在您的关系上执行此操作的正确语法是:
Event::whereHas('partecipants', function ($query) {
$query->where('IDUser', '=', 1);
})->get();
在https://laravel.com/docs/5.8/eloquent-relationships#eager-loading了解更多信息
附:它是“参与者”,非“参与者”。
@ Cermbo的回答与这个问题无关。在这个答案中,laravel
将给你所有Events
如果每个Event
有'partecipants'
与IdUser
是1
。
但是如果你想得到所有Events
所有的'partecipants'
,条件是每个'partecipants'
与IdUser
是1,那么你应该做这样的事情:
Event::with(["partecipants" => function($q){
$q->where('partecipants.IdUser', '=', 1);
}])
关注:
在哪里使用你的表名,没有模型名。