3张桌子之间的口才关系问题

时间:2019-06-01 21:50:40

标签: laravel eloquent relationship

我有这4张桌子:

events (id, name, date)
drivers (id, first_name, last_name)
participants (id, number, event_id, driver_id, codriver_id)
penalties (id, event_id, participant_id)

显示罚分表时如何获得驾驶员/副驾驶员的名字和姓氏?

我尝试过此方法,但不起作用:

$grid->participant()->driver()->full_name();
$grid->participant()->codriver()->full_name();

惩罚模型:

public function participant()
    {
        return $this->belongsTo(Participant::class);
    }

参与者模型:

public function driver()
    {
        return $this->belongsTo(Driver::class);
    }

    public function codriver()
    {
        return $this->belongsTo(Driver::class);
    }

驱动器型号:

public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }

我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:0)

->relation_name()返回关系查询生成器:

要获取一个或多个关系对象,您应该将关系称为属性,而不是函数(与full_name属性相同):

$grid->participant->driver->full_name;

等于:

$grid->participant()->first()->driver()->first()->full_name;