首页 > 解决方案 > Laravel 有一个通过

问题描述

在 laravel.com 上,有一个通过关系的示例,这几乎正是我所需要的。

https://laravel.com/docs/master/eloquent-relationships#has-one-through

mechanics
    id - integer
    name - string

cars
    id - integer
    model - string
    mechanic_id - integer

owners
    id - integer
    name - string
    car_id - integer

我的数据库结构完全一样。但是:在这个例子中,我认为每辆车都有一个所有者。我的问题是,我的车主有很多车,所以数据库有一点不同:

mechanics
    id - integer
    name - string

cars
    id - integer
    model - string
    mechanic_id - integer
    owner_id - integer

owners
    id - integer
    name - string

因此,代码示例不起作用:

class Mechanic extends Model
{
    /**
     * Get the car's owner.
     */
    public function carOwner()
    {
        return $this->hasOneThrough(Owner::class, Car::class);
    }
}

您是否有想法,如何更改接收代码:

//The mechanic
echo $mechanic->name;

//The cars the mechanic is working on
foreach ($mechanic->cars as car) {
    echo $car->model;

    //The owner of the car (Maybe like this???)
    echo $car->model->owner->name;
}

标签: laraveleloquent

解决方案


我不认为你想要 hasOneThrough 关系,除非你对一辆车感兴趣,而不是对机械师相关的每辆车感兴趣。

//The mechanic Model
dump($mechanic);

//The mechanic's name attribute
dump($mechanic->name);

//The Collection of cars associated with the mechanic
dump($mechanic->cars);

// echoing the model attribute of the cars associated with the mechanic
foreach ($mechanic->cars as $car) {
    echo $car->model;
}

// The owner of ONLY the first car associated with the mechanic
dump($car->carOwner);

// echoing the model attribute of the cars associated with the mechanic and the car owner's name;
foreach ($mechanic->cars as $car) {
    echo $car->model;
    echo $car->owner->name;
}
// Eager loading both cars and associated owners from the Mechanic model:
Mechanic::with('cars.owner')->...
// or
$mechanic->load('cars.owner');

推荐阅读