我对雄辩不是很熟悉。我有两个数据库模式。我已经尝试过使用和不使用 json 字段,但我找不到解决方案来获取:
附两张数据库图
我试过了
Object::withWhereHas('roles', function($query) {
$query->whereHas('users', function($query2){
$query2->where('id',auth()->id());
});
});
Object::with(['roles' => function($query){`your text`
$query->whereHas('users', function($query2){
$query2->where('id',auth()->id());
});
}]);
我向您寻求最佳程序的建议
为了满足您管理修改和删除对象的用户权限的要求,让我们首先分解问题:
can_modify
或can_delete
)。Eloquent 的关系和查询范围可以简化数据查询。以下是分步指南:
假设您有以下表格:
users
:存储用户信息。roles
:存储角色(例如管理员、编辑)。objects
:代表被管理的对象。role_user
:链接 users
和 roles
的数据透视表。object_role
:链接 objects
和 roles
的数据透视表。object_role
表可以包含 permission
字段(can_modify
、can_delete
)来存储特定权限。class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany(Role::class, 'role_user');
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'role_user');
}
public function objects()
{
return $this->belongsToMany(Object::class, 'object_role')->withPivot('permission');
}
}
class Object extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class, 'object_role')->withPivot('permission');
}
}
在
Object
模型中添加查询范围来过滤用户可以修改的对象:
class Object extends Model
{
public function scopeModifiableBy($query, $userId)
{
return $query->whereHas('roles', function ($query) use ($userId) {
$query->whereHas('users', function ($query) use ($userId) {
$query->where('id', $userId);
})->wherePivot('permission', 'can_modify');
});
}
}
用途:
$modifiableObjects = Object::modifiableBy(auth()->id())->get();
创建一个方法来检查登录用户是否可以删除特定对象:
class Object extends Model
{
public function canBeDeletedBy($userId)
{
return $this->roles()->whereHas('users', function ($query) use ($userId) {
$query->where('id', $userId);
})->wherePivot('permission', 'can_delete')->exists();
}
}
用途:
$object = Object::find($objectId);
if ($object->canBeDeletedBy(auth()->id())) {
// User can delete this object
} else {
// User cannot delete this object
}
您提到了获取未链接到角色的对象的问题。为了确保只检索相关对象:
has()
过滤链接到具有权限的角色的对象。示例:
$objects = Object::whereHas('roles', function ($query) {
$query->whereHas('users', function ($query) {
$query->where('id', auth()->id());
});
})->get();
role_user
、object_role
)已正确配置所有必需的关系和字段。dd()
、toSql()
)来检查查询并排除故障。role_id
、object_id
、user_id
)。对于更复杂的权限处理,请考虑使用 Laravel 策略。为
Object
模型定义策略并管理权限逻辑:
php artisan make:policy ObjectPolicy
在
ObjectPolicy
:
public function modify(User $user, Object $object)
{
return $object->roles()->whereHas('users', function ($query) use ($user) {
$query->where('id', $user->id);
})->wherePivot('permission', 'can_modify')->exists();
}
public function delete(User $user, Object $object)
{
return $object->roles()->whereHas('users', function ($query) use ($user) {
$query->where('id', $user->id);
})->wherePivot('permission', 'can_delete')->exists();
}
在控制器中:
if ($user->can('modify', $object)) {
// Logic for modifying the object
}
if ($user->can('delete', $object)) {
// Logic for deleting the object
}