我正在使用 Laravel 5.0 开发一个 Web API,但我不确定我正在尝试构建的特定查询。
我的课程如下:
class Event extends Model {
protected $table = 'events';
public $timestamps = false;
public function participants()
{
return $this->hasMany('App\Participant', 'IDEvent', 'ID');
}
public function owner()
{
return $this->hasOne('App\User', 'ID', 'IDOwner');
}
}
and
class Participant extends Model {
protected $table = 'participants';
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('participants')->where('IDUser', 1)->get();
but the where
条件应用于Event
而不是在其上Participants
。以下给了我一个例外:
Participant::where('IDUser', 1)->event()->get();
我知道我可以这样写:
$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
但向服务器发送这么多查询似乎效率不高。
执行任务的最佳方式是什么where
通过使用 Laravel 5 和 Eloquent 的模型关系?