Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

php - Laravel where on relationship object

I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build.

My classes are as follows:

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');
    }
}

and

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

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

I know that I can write this:

$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.

What is the best way to perform a where through a model relationship using Laravel 5 and Eloquent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct syntax to do this on your relations is:

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...