【问题标题】:Laravel - query depending on userLaravel - 根据用户查询
【发布时间】:2016-08-25 17:48:51
【问题描述】:

在 Laravel 中,我有一个场景,不同的用户可以转到视图刀片,在那里他们可以看到他们创建的帖子。

目前我只是传递所有数据,但我想知道如何根据用户将数据传递给视图。

例如,如果我是 root 用户,我可以看到所有类似的东西

Post::get()

然后

return view('someview', compact('post')

哪个会返回帖子

基本上我正在尝试的是这样的......

if(user->role = their role) then you get query 1 else you get query 2

您认为使用条件查询范围可以实现这一点吗?

更新

这是一个可怕的解决方案吗?

if($user->department == "Loans")
{
    echo "you are from loans FAM";
    $articles = Article::where('department', '=', 'Loans')->get();
} 
else if($user->department == "Digital")
{
    echo "you are from digital FAM";
    $articles = Article::where('department', '=', 'Digital')->get();
} 
else if($user->department == "Consulting")
{
    echo "you are from Consulting FAM";
    $articles = Article::where('department', '=', 'Consulting')->get();
} 

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果您愿意,可以使用查询范围来实现。像这样的:

    class Post extends Model
    {
        // ...
    
        public function scopeByUser($query, User $user)
        {
            // If the user is not an admin, show only posts they've created
            if (!$user->hasRole('admin')) {
                return $query->where('created_by', $user->id);
            }
    
            return $query;
        }
    }
    

    那么你可以这样使用它:

    $posts = Post::byUser($user)->get();
    

    响应您的更新:

    class Article extends Model
    {
        // ...
    
        public function scopeByUser($query, User $user)
        {
            // If the user is not an admin, show articles by their department.
            // Chaining another where(column, condition) results in an AND in
            // the WHERE clause
            if (!$user->hasRole('admin')) {
                // WHERE department = X AND another_column = another_value
                return $query->where('department', $user->department)
                    ->where('another_column', 'another_value');
            }
    
            // If the user is an admin, don't add any extra where clauses, so everything is returned.
            return $query;
        }
    }
    

    您可以按照与上述相同的方式使用它。

    Article::byUser($user)->get();
    

    【讨论】:

    • 基本上来自特定部门的用户应该只能查看该部门的文章。
    • 查看我更新的答案,而不是每个部门的 if 语句,您可以将部门值传递到查询中。
    • 老实说,这感觉像是一个更清洁的解决方案,我会尝试但我会回来的。
    • 可以和 where 一起使用 AND 吗?
    • 是的,当然,要做到这一点,您只需将另一个 where 链接到它上面。我会用一个例子来更新我的答案
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2013-08-31
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多