Laravel: error in creating relationship to get first child of each parent

I am trying to load the first child

entity of each object parent

as shown below:

$list = Parent::with('FirstChild')->get();

      

and the relationship defined in the model is parent

as follows:

public function FirstChild()
{
    return $this->hasMany('Child')->first();
}

      

but this throws an error:

BadMethodCallException thrown with message "Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()"

      

indicates that when I remove the method first()

then it works!

+3


source to share


1 answer


hasMany()

is to declare relationships with models (themselves or others). You've linked it to "Child" here, so when you delete first()

it works.

So this should work fine

$list = Parent::with('FirstChild')->first();

      



Edit can use hasOne () for first child and hasMany for ohter

public function FirstChild()
{
    return $this->hasOne('Child');
}
public function AllChild(){
   return $this->hasMany('Child');
}

      

+1


source







All Articles