2
说我有3个表:Laravel透视表无效外键
表1
+----+-------+
| id | name |
+----+-------+
| 1 | some |
| 2 | some2 |
+----+-------+
表2:
+----+-------+
| id | name |
+----+-------+
| 1 | some |
| 2 | some2 |
+----+-------+
table1_table2:
+-----------+-----------+---------------------+
| table1_id | table2_id | settings |
+-----------+-----------+---------------------+
| 1 | 1 | {'something':false} |
| 2 | null | {'something':false} | <--- :(
+-----------+-----------+---------------------+
然后我会在以下型号
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');
}
}
一切都是好的,当我在数据透视表这两个ID插入。
问题时(上数据检索),因为我有其中I插入空值table2_id案件。
Table1::find(1)->table2(); //Gives back the first entry OK (as array)
Table1::find(2)->table2(); //Gives back empty array
我的问题是:有没有一种方法,以纪念table2_id可选(这样Laravel使左连接,而不是正常的加入)?
嗯...是的,不要把它作为一个支点? :)您可以使用两个belongsTo关系,并使第二个可选。我想这会使逻辑更清洁。 –
我最终提出了解决方案,因为这是唯一不幸的方法。当你不得不从一个框架转换到另一个时很难:D –
很高兴它的工作。 :) –