Grid with Laravel 5.3 searching for the Foreign Keys

Asked

Viewed 152 times

1

Hello. I have an application where I need to mount a grid with all table data produtos. This table has Foreign Keys for two other tables, grupo and subgrupo. To mount my grid, I need the product array to have the group and subgroup id and all 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 don’t know how to mount 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"
  }
]

Also, as you may notice I needed to change the default "id" to "code", but this is already done. But I don’t know if this can affect the search.

I did some research before, but I couldn’t find what I needed, or maybe I didn’t do the right thing by not knowing Laravel’s used names. Can someone help me, please?

  • It has how to put the layout of the tables, in really not understood!

1 answer

0

You can bring it to your collection relationship data via the method withof the Eloquent ORM. Take a look here in the documentation to better understand. 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 a array rather a Collection (Illuminate\Database\Eloquent\Collection). But, I believe it is enough for you to iterate on and perform the operations you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.