Laravel在关系对象上的位置

问题描述 投票:36回答:2

我正在使用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的最佳方法是什么?

php laravel eloquent where relationship
2个回答
113
投票

在您的关系上执行此操作的正确语法是:

Event::whereHas('partecipants', function ($query) {
    $query->where('IDUser', '=', 1);
})->get();

https://laravel.com/docs/5.8/eloquent-relationships#eager-loading了解更多信息

附:它是“参与者”,非“参与者”。


11
投票

@ Cermbo的回答与这个问题无关。在这个答案中,laravel将给你所有Events如果每个Event'partecipants'IdUser1

但是如果你想得到所有Events所有的'partecipants',条件是每个'partecipants'IdUser是1,那么你应该做这样的事情:

   Event::with(["partecipants" => function($q){
                $q->where('partecipants.IdUser', '=', 1);
            }])

关注:

在哪里使用你的表名,没有模型名。

© www.soinside.com 2019 - 2024. All rights reserved.