本文介绍了Laravel在关系对象上的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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('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');
    }
}

现在,我想让特定参与者参加所有活动.我尝试过:

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

更多信息,请参见 https://laravel.com/docs/5.8/eloquent -relationships#eager-loading

这篇关于Laravel在关系对象上的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:21