Getting reference values ​​with distant relationships in Laravel

In my Laravel project, I used the following ( inspired here ) to get a distant relationship from model to another. I can not use the HasManyThrough method , since the bars and bazs are associated with a polymorphic relation.

public class MyClass 
{
    public function foos()
    {
        return $this->hasMany('App\Foo');
    }

    public function getBazAttribute()
    {
        $this->load(['foos.bars.bazs' => function ($q) use (&$bazs) {
            $bazs = $q->get()->unique();
        }]);
    }
}

This works as expected and returns bazs that are associated with bars that are related to foos that are associated with a MyClass object . My problem is that I don’t know how I can use this to easily get things like:

  • foos, baz
  • foos, baz

. foos foos, bazs

+4
2

.

- , , foos , - $bazs :

$bazs->load('bars.foos');

, , Accessor baz:

public function getFoosAttribute()
{
    $foos = \Illuminate\Database\Eloquent\Collection::make([]);
    foreach ($this->bars as $bar) {
        $foos->merge($bar->foos);
    }
    return $foos;
}

, , foos:

foreach ($bazs as $baz) {
    // get all baz foos way
    $foosOfBaz = $baz->foos;

    //when we have them all in collection we can easily count them
    $foosOfBaz->count() 
}

foos ,

foos, baz , /foreach , (bazs it bars) :

$bazs->load('bars.foos');

foreach ($bazs as $baz) {
    foreach ($baz->bars as $bar) {
        //here You can access the foos collection 
        //that is from bar that belongs to baz model object
        $bar->foos;
    }
}

: , : $bar->foos->toArray() ->pluck('filed_name', 'key_name')->toArray()

0

, . . :

:

Table A    Table B    Table C    Table D
  1           a          x         I 
  2           b          y         II
  3           c          z         III

A, B B, C C D.

, A D . D, A.

.

This is one of my long relationship projects. , , , . . , . , . , , front-end. .

, , , , , . , .

0

All Articles