由于team_id在我的tickets表中是可选的,我已经将其设置为可以为null,但它仍然是teams表的外键,但当我尝试获取与teams表有关系的多行ticket时,具有team_id的ticket会正确返回,但具有null team_id会中断程序并返回此错误"Trying to get property of non-object"。
迁移:
Schema::create('tickets', function (Blueprint $table) {
$table->integer('team_id')->unsigned()->nullable();
});
Schema::table('tickets', function (Blueprint $table) {
$table->foreign('team_id')
->references('id')
->on('teams');
});
票据型号
public function team()
{
return $this->belongsTo('App'Models'Team', 'team_id', 'id');
}
团队模型
public function tickets()
{
return $this->hasMany('App'Models'Ticket', 'id', 'team_id');
}
票据控制器
$tickets = Ticket::orderBy('created_at', 'desc')
->take(10)
->get();
foreach ($tickets as $ticket) {
var_dump($ticket->team->name);
}
会的,因为对于team_id
为null的行,$ticket->team
不存在。
你可以做这个
foreach ($tickets as $ticket) {
if($ticket->team){
var_dump($ticket->team->name);
}
}
外键在所有条件下都是外键,没有办法实现只有当表不为null时才会查找表的条件外键约束。在最好的情况下(或者更确切地说,在最坏的情况下),您可以向它要查找的主键表添加一个NULL值。