簡體   English   中英

定義“advance”具有一對多的關系,該關系檢索具有特定角色的用戶所做的最后(許多)記錄

[英]Defining "advance" has-one-of-many relationship that retrieve the last (of many) record made by user with specific role

假設我有存儲用戶創建的任何“帖子”的Post model,以及存儲Post model 的更改日志的PostLog模型。顯然, PostPostLoghasMany()關系。

現在我想從這種關系中定義一個“多中之一”。 PostLoguser_id ,它定義了進行更改的用戶。 我想檢索具有特定角色的用戶創建的最新PostLog

對於usersroles表,他們的關系是多對多的,也就是說有role_user連接他們兩個。

這是我想出的最好的,但我沒有得到正確的值(顯然):

class Post extends Model
{
    public function latestAdminPostLog()
    {
        return $this->hasOne(PostLog::class)->ofMany([
            'id' => 'max',
            'created_at' => 'max'
        ], function ($query) {
            $query->whereExists(function ($qry) {
                $qry->select(DB::raw(1))
                    ->from('users')
                    ->join('role_user', 'users.id', '=', 'role_user.user_id')
                    ->join('roles', 'role_user.role_id', '=', 'roles.id')
                    ->whereColumn('users.id', 'post_logs.user_id')
                    ->whereIn('roles.name', ['admin-x', 'admin-y']);
            });
        });
    }
}

非常感謝您的幫助。 謝謝!

注意:我使用santigarcor/laratrust package 進行用戶角色管理。

做就是了

public function latestAdminPostLog(){
     return $this->hasOne(PostLog::class)->whereHas('user', fn (Builder $query) => $query->whereRoleIs(['admin-x', 'admin-y']))->latest();
}

這將返回由具有 admin-x 或 admin-y 角色的用戶創建的最新 PostLog

祝你今天過得愉快

暫無
暫無

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

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