我正在使用 Laravel 5.0 开发 Web API,但我不确定要构建的特定查询。
我的类(class)如下:
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');
}
}
和
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();
但是 where
条件应用于 Event
而不是应用于其 Participants
。以下给了我一个异常(exception):
Participant::where('IDUser', 1)->event()->get();
我知道我可以这样写:
$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
但是向服务器发送这么多查询似乎效率不高。
使用 Laravel 5 和 Eloquent 通过模型关系执行 where
的最佳方法是什么?
最佳答案
对关系执行此操作的正确语法是:
Event::whereHas('participants', function ($query) {
return $query->where('IDUser', '=', 1);
})->get();
这将返回参与者的用户 ID 为 1 的事件。如果参与者的用户 ID 不是 1,则不会返回事件。
阅读更多信息 https://laravel.com/docs/5.8/eloquent-relationships#eager-loading
关于php - Laravel 在关系对象上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989908/