如何在Laravel中为hasOne()关系指定数据透视表


How to specify pivot table for hasOne() relationship in Laravel

我有几个模型,我已经包含了数据透视表,以避免多态关系。

role table
id
name
description
restriction table
id
rule
status
restriction_role table
id
restriction_id
role_id

这样设置的原因是角色和限制实际上可以属于多个其他模型。在这种情况下,一个角色只能有1个限制。我通常会将其定义为

class Role extends Eloquent {
    public function restrictions()
    {
        return $this->hasOne('Restriction');
    }
}

这显然不起作用,因为Laravel不知道连接此关系的数据透视表。我可以通过使用多对多关系来轻松实现这一点,但这并不是我的模型的工作方式。在文档中没有看到任何定义它的内容。任何想法吗?

我通过使用belongsToMany关系并为它定义一个自定义访问器来解决这个问题,如下所示:

public function foo()
{
    return $this->belongsToMany(App'Bar::class);
}
public function getFooAttribute()
{
    return $this->foo()->first();
}

正如@deczo在评论中所述,belongsToMany()是这里的全部工作。如果您只需要一个结果,但不能使用hasOne()关系,我建议使用first()方法返回第一个结果。