簡體   English   中英

如何在 Eloquent ORM 中使用此方法?

[英]How can I make this method in Eloquent ORM?

Hlw,我是 php、laravel 的新來者,你能解釋一下我如何用 laravel 替換這個查詢生成器 Elouquet 來創建這個isAuthorized()方法嗎?

class User extends Authenticatable
{
    public function isAuthorized($object, $operation)
    {
        return Db::table('role_permissions')
            ->where('object', $object)
            ->where('operation', $operation)
            ->join('user_roles', 'user_roles.role_id', '=', 'role_permissions.role_id')
            ->where('user_roles.user_id', $this->id)
            ->exists();
    }
}

像這樣創建你的模型。

public class RolePermission {
    public function UserRoles() {
        return $this->hasMany(UserRole::class, 'role_id', 'role_id');
    }
}

public class UserRole {

}

WhereHas可以查詢關系,是替換聯接的基石。

RolePermission::where('object', $object)
    ->where('operation', $operation)
    ->whereHas('UserRoles', function ($query) {
        $query->where('user_roles.user_id', $this->id)
    })     
    ->exists();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM