Laravel 在关系对象上

Laravel where on relationship object

我正在使用 Laravel 5.0 开发网络 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');
    }
}

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。以下给了我一个例外:

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();

这将 return 参与者的用户 ID 为 1 的事件。如果参与者的用户 ID 不是 1,则事件将不会 returned。

https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

阅读更多内容

@Cermbo 的回答与本题无关。在那个答案中,如果每个 Event'participants'IdUser of 1Laravel 会给你全部 Events

但是如果你想获得所有 Events 和所有 'participants',前提是所有 'participants'IdUser 都为 1,那么你应该这样做:

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

N.B:

where 中使用您的 table 姓名,而不是模特姓名。

使用此代码:

return Deal::with(["redeem" => function($q){
    $q->where('user_id', '=', 1);
}])->get();

对于多个连接,使用如下代码:

$userId = 44;
Event::with(["owner", "participants" => function($q) use($userId ){
    $q->where('participants.IdUser', '=', 1);
    //$q->where('some other field', $userId );
}])

我在 BaseModel 中创建了一个自定义查询范围(我的所有模型都扩展了这个 class):

/**
 * Add a relationship exists condition (BelongsTo).
 *
 * @param  Builder        $query
 * @param  string|Model   $relation   Relation string name or you can try pass directly model and method will try guess relationship
 * @param  mixed          $modelOrKey
 * @return Builder|static
 */
public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
{
    if ($relation instanceof Model && $modelOrKey === null) {
        $modelOrKey = $relation;
        $relation   = Str::camel(class_basename($relation));
    }

    return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
        return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
    });
}

您可以在许多情况下使用它,例如:

Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1 

此外,您可以尝试省略关系名称并仅传递模型:

$participant = Participant::find(1);
Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance

[OOT]

有点OOT,不过这个问题和我的问题最接近。

这里是一个例子,如果你想显示 ALL 参与者满足特定要求的事件。比方说,所有参与者 全额支付 的事件。因此,它不会 return 有一名或多名参与者尚未全额付款的活动。

只需使用其他2种状态中的whereDoesntHave

假设状态是完全未支付 [eq:1]、支付了部分 [eq:2] 和全额支付 [eq:3]

Event::whereDoesntHave('participants', function ($query) {
   return $query->whereRaw('payment = 1 or payment = 2');
})->get();

测试于 Laravel 5.8 - 7.x

对于 laravel 8 改用这个

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

这将 return 仅与用户 ID 为 1 的参与者具有该事件关系的事件,

为laravel 8.57+

Event::whereRelation('participants', 'IDUser', '=', 1)->get();