简体   繁体   中英

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

I have a couple of models that I have included pivot tables for to avoid a polymorphic relation.

role table
id
name
description

restriction table
id
rule
status

restriction_role table
id
restriction_id
role_id

Reason for this setup is that both Roles and Restrictions can actually belong to multiple other models. In this case, a Role can only have 1 Restriction. I would normally define this as

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

This obviously does not work because Laravel is unaware of the pivot table connecting this relation. I could easily accomplish this by using a many-to-many relationship instead, but this is not exactly how my model works. Not seeing anything in the documentation for defining this. Any thoughts?

I've solved this by using the belongsToMany relation and defining a custom accessor for it, like so:

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

public function getFooAttribute()
{
    return $this->foo()->first();
}

As @deczo stated in the comments, belongsToMany() is about all that will work here. I recommend returning the first result using the first() method if you require only one result but cannot use a hasOne() relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM