我具有以下多态关系:
// 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
。
答案 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();