Laravel 关系 null 外键提取

Laravel relationship null foreign key fetching

由于 team_id 在我的票 table 中是可选的,我已将其设置为可为空但仍然是团队的外键 table,但是当我尝试获取与团队 table 相关的多行票证,具有 team_id returns 的票证正确但具有空值 team_id 的票证会破坏程序并 returns 此错误"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);
}

外键在所有条件下都是外键,无法实现仅在 table 不为 null 时才查找的条件外键约束。最好的情况(或者更确切地说,最坏的情况),您可以将 NULL 值添加到它正在查找的主键 table 中。

会的,因为 $ticket->team 对于 team_id 为空的行不存在。

你可以这样做

foreach ($tickets as $ticket) {
    if($ticket->team){
        var_dump($ticket->team->name);
    }
}