Miguel Ramirez
Miguel Ramirez

Reputation: 83

Return array with all children from a parent table Eloquent

Im using LARAVEL 5.7 and i have 2 tables called "parent_table" with "parent_id,parent_name" and "children_table" with "children_id,children_name". And i have 2 models with the same names of the tables with the following code:

Parent Model

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

Children Model

public function parent()
{
    return $this->belongsTo('App\parent', 'parent_id');
} 

I have a controller with this code

$data = App\parent::with("children")->get();
return $data;

But it returns me only the first children of every "parent". I want to know what i need to add to the code to get all the children of every parent.

I already try to get all the "parents" and the foreach all the "children" but it would be to many request to database. thanks!

Upvotes: 0

Views: 4287

Answers (3)

Miguel Ramirez
Miguel Ramirez

Reputation: 83

After several hours i found the solution. I didn´t know that it was important to make the select to the foreign key... that's why my query wasn´t working.

Final Parent Model

 public function children()
 {
    return $this
                ->hasMany('App\children',"parent_id")
                ->select(
                    "children_id",
                    "children_nombre",
                    "parent_id"//I wasn't selecting this guy
                )
                //->with("children2") // With this i got the way to concatenate a lot of subchildren map :D
                ;
 }

Final children model

public function parent()
{
    return $this->belongsTo('App\parent',"parent_id","parent_id");
}

Controller

$data = App\parent::
                select(
                    "parent_id",
                    "parent_nombre"
                )
                ->with("children")
                ->get();

    return $data;

I learn something new today, I hope this answer helps to other laravel learners too

Upvotes: 1

ggirodda
ggirodda

Reputation: 790

Using with as you did in your exemple will work. Maybe you have to put 'children' in the $appends array on your model.

namespace App;
class Parent {
  ...
  protected $appends = ['children'];
  ...
}

this will appends the children result when the model are transformed into array

Upvotes: 0

Piazzi
Piazzi

Reputation: 2636

You can do something like this:

 @foreach($parents as $parent)
{
  $parent->children();
}

This should return a collection from the Children model. For more info you can look here: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many

Upvotes: 1

Related Questions