Grid with Laravel 5.3 looking for foreign keys

1

Hello. I have an application where I need to mount a grid with all the data in the produtos table. This table has foreign keys for two other tables, grupo and subgrupo . To mount my grid, I need the array with the products to have the group and subgroup id and all the other information contained in an array.

My method in the controller:

public function grid(){
    return \App\produto::all();
}

The product model has:

public function grupo(){
    return $this->hasMany('App\grupo');
}

public function subgrupo(){
    return $this->hasMany('App\subgrupo');
}

But I do not know how to build the grid using this. I need the return array to look something like this:

[
  {
  "codigo": 3,
  "grupo": [
    {
      "codigo": 1,
      "descricao": "Descrição do grupo"
    }    
  ],
  "subgrupo": [
    {
      "codigo": 1,
      "descricao": "Descrição do subgrupo"
    }
  ],
  "descricao": "1"
  }
]

In addition, as you may notice I needed to change the default "id" to "code", but this is already done. But I do not know if this could affect the search.

I searched before but did not find what I needed, or maybe I did not search the right thing for lack of knowledge of Laravel's used names. Can someone help me, please?

    
asked by anonymous 01.03.2017 / 20:13

1 answer

0

You can bring your relationship data through the collection using the with method of Eloquent ORM. Take a look at here in the documentation to understand better. In your case it would look something like this:

public function grid(){
    return \App\produto::with('grupo', 'subgrupo')->all();
}

Remembering that what will be returned from this function is not an array but rather a collection ( Illuminate\Database\Eloquent\Collection ). But, I think it's enough for you to iterate over and perform the operations you want.

    
04.03.2017 / 18:41