samedi 25 mai 2019

Laravel collection 2nd result set relationship always null

I have a query where I'm returning a one to many relationship I'm expecting two results both with their relationship. The first result returns correctly but after the first result, I always get a NULL value for my relationship data for every result after the first.

If I delete the 1st record in my database the 2nd then becomes the first and it returns correctly.

This is my query -

$groups = DataGroup::where('post_id', $post->id)->with('data.dataType')->get();

DataGroup relationship

public function data()
{
    return $this->hasMany('App\Data', 'data_group_id');
}

Data relationships

public function dataType()
{
    return $this->belongsTo('App\DataTypes', 'id');
}

public function dataGroup()
{
    return $this->belongsTo('App\DataGroup', 'id');
}

DataType relationship

public function data()
{
    return $this->hasMany('App\Data', 'data_types_id');
}

The result set (stripped out other information for easier reading)

Collection {#259 ▼
  #items: array:2 [▼
    0 => Data {#272 ▼
      #fillable: array:5 [▶]
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #relations: array:1 [▼
        "dataType" => DataTypes {#271 ▶}
      ]
    }
    1 => Data {#268 ▼
      #fillable: array:5 [▶]
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #relations: array:1 [▼
        "dataType" => null
      ]



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2YT8iwF
via IFTTT

Aucun commentaire:

Enregistrer un commentaire