ka_lin
ka_lin

Reputation: 9442

Laravel pivot table null foreign key

Say that I have 3 tables:

table1

+----+-------+
| id | name  |
+----+-------+
|  1 | some  |
|  2 | some2 |
+----+-------+

table2:

+----+-------+
| id | name  |
+----+-------+
|  1 | some  |
|  2 | some2 |
+----+-------+

table1_table2:

+-----------+-----------+---------------------+
| table1_id | table2_id |      settings       |
+-----------+-----------+---------------------+
|         1 | 1         | {'something':false} |
|         2 | null      | {'something':false} | <--- :(
+-----------+-----------+---------------------+

Then I would have the following models

class Table1 extends Model {
    [...]
    public function table2()
    {
        return $this->belongsToMany('Table2', 'table1_table2', 'table1_id', 'table2_id')
            ->withPivot('settings');
    }
}

class Table2 extends Model {
    [...]
    public function table1()
    {
        return $this->belongsToMany('Table1', 'table1_table2', 'table2_id', 'table1_id')
            ->withPivot('settings');
    }
}

Everything is okay when I insert in the pivot table both id's.

Problem occurs(on data retrieval) because I have cases where I insert null values in table2_id.

Table1::find(1)->table2(); //Gives back the first entry OK (as array)
Table1::find(2)->table2(); //Gives back empty array

My question is: Is there a way to mark table2_id as optional (so that Laravel makes a left join rather than a normal join)?

Upvotes: 2

Views: 687

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25404

The easiest way is probably to just skip the pivot entirely, and make it a regular table + model which belongsTo both tables, but the latter one optionally.

Upvotes: 1

Related Questions