archvist
archvist

Reputation: 722

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
      ]

Data Groups Table

---------------------
| id | post_id      |
--------------------
| 1  | 2            |
--------------------

Data Types table

---------------------
| id | label | name |
--------------------
| 1  | Text  | text |
--------------------

Data table

------------------------------------------------------------
| id | data_types_id | data_group_id | field_label | value |
------------------------------------------------------------
| 1  |  1            | 1             | Title       | NULL  |
------------------------------------------------------------
| 2  |  1            | 1             | Sub Heading | NULL  |

Upvotes: 0

Views: 45

Answers (1)

Techno
Techno

Reputation: 1696

I believe if you change:

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

into:

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

that should resolve the problem, it is currently trying to refer to a datatype with id 2(which is the id of data 2), which does not exist.

Look at the lower part of the https://laravel.com/docs/5.8/eloquent-relationships#one-to-one paragraph, it describes you need to enter foreign key as 2nd variable of the relationship definition, not the local key.

BTW: Your other relationship has the same problem:

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

Upvotes: 1

Related Questions