Search code examples
phplaravellaravel-8eloquent-relationship

Laravel HasManyThrough 3 Tables Return to Nested Array


I'm currently working with HasManyThrough() laravel relationship, and i get struggle with my case.. Here's an example:

My Tables look like theese:
Quotations
   id
   name

Service
   id
   quotations_id
   name

Work
   id
   service_id
   name

i want an array return like these:

[0]: {
      id: 1,
      name: Quotation 1,
      service: [
          [0]: {
                 id: 1
                 name: Service 1,
                 quotation_id: 1,
                 work: [
                    [0]: {
                          id: 1,
                          name: work 1,
                          service_id: 1
                       },
                    [1]: {...}
                 ]
           }
         [1]: {...}
     [
},
{....}

I'm already try it with HasManyThrough() in Quotations Model:

public function service()
{
    return $this->hasMany(Service::class);
}

public function work()
{
    return $this->hasManyThrough(Work::class, Service::class);
}

And get return in Quotations Controler :

$quotation = Quotation::with('service')->get()->load('work);

But i get diferent array result:

[0]: {
        id: 1,
        name: Quotation 1,
        service: [0]: {...},
        work: [0]: {...},
}

How do i get with HasManyThrough relationship..? or can i get it with HasManyThrough Relationship...? Thanks before..


Solution

  • It's done.. I've change my Controller to this:

    $quotation = Quotation::with('service.work')->get();