【问题标题】:Eloquent relationships question between 3 tables3张表之间的雄辩关系问题
【发布时间】:2019-10-18 00:35:01
【问题描述】:

我有这 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;
    }

我该怎么办?

谢谢

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

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

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

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

    以下是:

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

    【讨论】:

    • 谢谢,但我需要作为函数调用。例如$grid->participant()->number() 工作正常,但$grid->participant()->driver()->full_name();不行。
    猜你喜欢
    • 2017-08-28
    • 1970-01-01
    • 2019-11-06
    • 2020-07-23
    • 2018-07-24
    • 2019-07-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多