Laravel get owned by ToMany through hasMany

I have 3 models: Conference , Session and Speaker . A conference can have many sessions, and many sessions can have many speakers.

Database structure

 conferences ----------- id name sessions -------- id conference_id name session_speaker --------------- id session_id speaker_id speakers -------- id name 

I need to write a method that allows me to get all the speakers for a particular conference (so that all speakers from all sessions of that particular conference).

The following illustrates what I think should work, but obviously this is not the way I cannot tie them together.

application / models / Conference.php

 class Conference extends Eloquent { public function speakers() { return $this->hasMany('Session')->belongsToMany('Speaker'); } } 

I have all the model-model relationships established and working correctly (Conference-Sessions, Session-Speakers), but I can’t create a bridge between the conference-speaker sessions. Does anyone know how I can achieve this without writing a large SQL join query?

I think that if the belongsToManyThrough() relationship existed, it would work, but it would not.

Thanks in advance!

+6
source share
1 answer

Unfortunately, the hasManyThrough relationship does not work with many, many relationships between them.

What you can do is something like this:

 public function speakers() { $session_ids = Session::where('conference_id', $this->id); $speaker_ids = DB::table('session_speaker')->whereIn('session_id', $session_ids)->lists('speaker_id'); return Speaker::whereIn('id', $speaker_ids)->get(); } 

You probably need to set the variables to array(0) if no results are found, otherwise the whereIn function will throw an error. You can also use the "Only One Person" method, but this is likely to result in a much larger number of database queries, while this should be fine when only 2 queries are executed.

Then you can access the speakers, for example. Conference::find(1)->speakers() .

+7
source

Source: https://habr.com/ru/post/970740/


All Articles