Lic*_*Lic 46 php relationship where-clause laravel eloquent
我正在使用Laravel 5.0开发web apis,但我对查询有疑问.我的课程是:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
和
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');
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望用特定的partecipant获取所有事件.我尝试过:
Event::with('participants')->where('IDUser', 1)->get();
Run Code Online (Sandbox Code Playgroud)
但where条件适用于Event的类而不是Partecipants.这给了我一个例外:
Participant::where('IDUser', 1)->event()->get();
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样写:
$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
Run Code Online (Sandbox Code Playgroud)
但是没有对服务器运行太多查询?
那么,使用Laravel和Eloquent执行此查询的最佳方法是哪里?
Cre*_*mbo 138
在您的关系上执行此操作的正确语法是:
Event::whereHas('participants', function ($query) {
$query->where('IDUser', '=', 1);
})->get();
Run Code Online (Sandbox Code Playgroud)
更多信息,请访问https://laravel.com/docs/5.0/eloquent#eager-loading
PS它是"参与者",而不是"参与者".
小智 60
适用于 Laravel 8.57+
Event::whereRelation('participants', 'IDUser', '=', 1)->get();
Run Code Online (Sandbox Code Playgroud)
Ham*_*our 25
@Cermbo的答案与此问题无关。在这个答案,Laravel会给大家Events如果每个Event具有'participants'与IdUser是1。
但是,如果您希望获得所有Events与all一起'participants'提供的条件,并且per 'partecipants'with IdUser为1,则应该执行以下操作:
Event::with(["participants" => function($q){
$q->where('participants.IdUser', '=', 1);
}])
Run Code Online (Sandbox Code Playgroud)
注意:
使用表名的地方,没有模型名。
Muh*_*zad 12
对于多个连接,请使用以下代码:
$userId = 44;
Event::with(["owner", "participants" => function($q) use($userId ){
$q->where('participants.IdUser', '=', 1);
//$q->where('some other field', $userId );
}])
Run Code Online (Sandbox Code Playgroud)
小智 7
对于 laravel 8 使用这个代替
Event::whereHas('participants', function ($query) {
$query->where('user_id', '=', 1);
})->get();
Run Code Online (Sandbox Code Playgroud)
这将返回仅与用户 ID 为 1 且具有该事件关系的参与者相关的事件,
return Deal::with(["redeem" => function($q){
$q->where('user_id', '=', 1);
}])->get();
Run Code Online (Sandbox Code Playgroud)
这对我有用