jeudi 26 avril 2018

Laravel Eloquent Relation Query - Get data along with relation attribute

I need help to retrieve eloquent relational data.

Let's say I have this eloquent relation:

Model & Relation

  1. Company
    Attribute : (id, code, name, status)
    Relation :

    public function sites(){
    $this->hasMany(\App\Models\Site::class);
    }

  2. Site
    Attribute : (id, company_id, code, name, status)
    Relation :

    public function company(){
    $this->belongsTo(\App\Models\Company::class);
    }


What I want to retrieve

I want to retrieve all site data along with it's company name, e.g:

[
   {
      "id":7,
      "company_id":1,
      "company_name":"Company 1",
      "code":"S001",
      "name":"Site 001",
      "status":"Active"
   },
   {
      "id":8,
      "company_id":1,
      "company_name":"Company 1",
      "code":"S002",
      "name":"Site 002",
      "status":"Active"
   }
]


What I already tried

  1. I've already tried with this method:

    $sites = Site::with('company')->get();
    dd($sites->toJson());

but it gives me:

[
   {
      "id":7,
      "company_id":1,
      "code":"S001",
      "name":"Site 001",
      "status":"Active",
      "company":{
         "id":1,
         "code":"C001",
         "name":"Company 1",
         "status":"Active"
      }
   },
   {
      "id":8,
      "company_id":1,
      "code":"S002",
      "name":"Site 002",
      "status":"Active",
      "company":{
         "id":1,
         "code":"C001",
         "name":"Company 1",
         "status":"Active"
      }
   },
]

  1. For now, I use this way to get the data. But I think there's another best way without loop the whole data just to get some specific relation attribute:

    $sites = Site::get();
    foreach ($sites as $site){
    $site['company_name'] = $site->company()->first()->name;
    }
    dd($sites->toJson());

My question

Actually, how is the best way to get the data I want? Is it possible to not use loop and just use Eloquent relation query? Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HWfnrv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire