0

有3种型号:

First (first_id)
Connection (connection_id, first_id, product_id)
Second (second_id, product_id)

我想使用 laravel 关系将三个模型连接在一起

First->虽然加入了连接first_id Connection-> 加入了 First through first_id, & 加入了Second通过product_id Second-> 加入了 Connection throughproduct_id

所以:首先通过 Connection 加入到 Second first_idproduct_id

这可以使用类似的东西HasManyThrough吗?

谢谢你的时间

4

3 回答 3

1

在您的第一个模型上:

public function second () {
    return $this->hasManyThrough(
        Second::class, 
        Connection::class, 
        'product_id', // Foreign key on connection table
        'product_id', // Foreign key on second table
        'first_id', // Local key on first table
        'first_id' // Local key on connection table
    );
}

根据您的描述,列名应该可以工作。

在修补程序中,您可以通过执行类似First::first()->second.

于 2019-05-13T13:50:45.937 回答
1

这取决于您的第一个模型和第二个模型共享什么类型的关系,以及第二个和第三个模型共享什么类型的关系。

如果考虑您的第一个模型First和第二个模型Second共享一对一的关系,并且Second模型和Third模型共享一对一的关系。

它将是$first->second->third;//没有很多直通关系要求

如果您的First模型和Second模型共享为 hasMany-belongs 关系而不是您需要使用 hasManyThrough 关系

文档中的示例

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}
于 2019-05-13T13:53:17.703 回答
1

您可以尝试使用嵌套关系。

嵌套急切加载 要急切加载嵌套关系,您可以使用“点”语法。例如,让我们在一个 Eloquent 语句中急切地加载本书的所有作者和作者的所有个人联系人:

$books = App\Book::with('author.contacts')->get();

图书型号:

public function author() 
{
    return $this->hasOne('App\Author');
}

作者型号:

public function contacts() 
{
    return $this->hasMany('App\Author');
}

文档:

https://laravel.com/docs/5.8/eloquent-relationships

于 2019-05-13T13:53:44.540 回答