Laravel多态关系范围的枢轴字段

时间:2019-06-26 13:45:44

标签: laravel eloquent

我具有以下多态关系:

// User.php
public function regions()
{
    return $this->morphedByMany('App\Region', 'relationship')->withPivot('relationship_level');
}

public function groups()
{
    return $this->morphedByMany('App\Group', 'relationship')->withPivot('relationship_level');
}

数据透视表如下:

id | user_id | relationship_id | relationship_type | relationship_level
 1 |      12 |               8 |        App\Region |             master
 2 |      18 |              12 |         App\Group |                fan

有什么方法(最好是范围)可以让每个拥有“ {master”级别的用户,只要该用户可以有许多relationship level到许多relationship_type

1 个答案:

答案 0 :(得分:0)

使用现有关系:

User::whereHas('groups', function ($query) {
    $query->where('relationship_level', 'master');
})->orWhereHas('regions', function ($query) {
    $query->where('relationship_level', 'master');
})->get();

使用数据透视模型和新关系(更快):

class Relationship extends \Illuminate\Database\Eloquent\Relations\MorphPivot
{
    //
}

class User extends Model
{
    public function relationships()
    {
        return $this->hasMany(Relationship::class);
    }
}

User::whereHas('relationships', function ($query) {
    $query->where('relationship_level', 'master');
})->get();