php - Laravel complex query with eloquent -


i'm new laravel , eloquent , can't find example of i'm trying , lets have 3 tables b c , , of them have many many relations ships a - ab - b - bc - c.

ab : table contains key , b. bc : table contains key b , c. 

what if want find c objects using (a_id = 1) ?

i tried a::find(1) -> b() -> c()->get() ;

b() method created b objects in model. c() method created c objects in b model. 

what doing wrong ? hope question , example clear.

best regards.

eloquent offers hasmanythrough relationship shortcut, supports one-to-many relations between models. there various workarounds in this thread on laravel.io forum. following short solution taken that thread i've tested , has worked. needs added base model models extend:

public function manythroughmany($related, $through, $firstkey, $secondkey, $pivotkey) {     $model = new $related;     $table = $model->gettable();     $throughmodel = new $through;     $pivot = $throughmodel->gettable();      return $model         ->join($pivot, $pivot . '.' . $pivotkey, '=', $table . '.' . $secondkey)         ->select($table . '.*')         ->where($pivot . '.' . $firstkey, '=', $this->id); } 

then on a model can define relation method returns this:

public function c() {     return $this->manythroughmany('c', 'b', 'b_id', 'id', 'c_id'); } 

and access related entries so:

a::find(1)->c()->get(); 

there's class defining relation purpose in thread, haven't tested can't if works properly.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -