問題描述
我正在使用 Laravel 5.0 開發 Web API,但我不確定我正在嘗試構建的特定查詢.
I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build.
我的課程如下:
class Event extends Model {
protected $table = 'events';
public $timestamps = false;
public function participants()
{
return $this->hasMany('AppParticipant', 'IDEvent', 'ID');
}
public function owner()
{
return $this->hasOne('AppUser', 'ID', 'IDOwner');
}
}
和
class Participant extends Model {
protected $table = 'participants';
public $timestamps = false;
public function user()
{
return $this->belongTo('AppUser', 'IDUser', 'ID');
}
public function event()
{
return $this->belongTo('AppEvent', 'IDEvent', 'ID');
}
}
現在,我想獲取特定參與者的所有事件.我試過:
Now, I want to get all the events with a specific participant. I tried with:
Event::with('participants')->where('IDUser', 1)->get();
但是 where
條件應用于 Event
而不是它的 Participants
.以下給了我一個例外:
but the where
condition is applied on the Event
and not on its Participants
. The following gives me an exception:
Participant::where('IDUser', 1)->event()->get();
我知道我可以寫這個:
$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
但是向服務器發送這么多查詢似乎效率不高.
but it doesn't seem very efficient to send so many queries to the server.
使用 Laravel 5 和 Eloquent 通過模型關系執行 where
的最佳方法是什么?
What is the best way to perform a where
through a model relationship using Laravel 5 and Eloquent?
推薦答案
對您的關系執行此操作的正確語法是:
The correct syntax to do this on your relations is:
Event::whereHas('participants', function ($query) {
return $query->where('IDUser', '=', 1);
})->get();
這將返回參與者的用戶 ID 為 1 的事件.如果參與者的用戶 ID 不為 1,則不會返回該事件.
This will return Events where Participants have a user ID of 1. If the Participant doesn't have a user ID of 1, the Event will NOT be returned.
在 https://laravel.com/docs/5.8/eloquent 閱讀更多-relationships#eager-loading
這篇關于Laravel 在關系對象上的位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!