繁体   English   中英

Laravel Eloquent 使用角色获取存储在类别中的所有帖子

[英]Laravel Eloquent get all Posts stored in categories with Roles

我在名为的数据库中有四个表: CategoryUserRolePost Category表中,我有一个category_id列,通过该列,我可以在类别中有多个子项。

每个user属于多个rolescategories以及每个category多个posts我必须按登录到我们的应用程序的role获取所有帖子

正如您在下面的屏幕截图中看到的那样, manager 2 manager 1manager 2属于多个programingsdartflutterphp

在此处输入图片说明

你可以假设manager 1用户 id 是1并且manager 22并且他们都是manager角色

我的问题是如何按role获取已登录用户属于多个categories的所有帖子

登录的用户是manager 1 ,我想从父级那里获取所有保存到类别中的帖子,即PROGRAMINGS

例如:

$categories = Category::whereNull('category_id')->whereHas('users.roles', function($q){
    return $q->whereLabel('is-manager');
})->with(['posts' => function ($query) {
    $query->with('language');
}])->get();
dd($categories->pluck('posts'));

笔记:

与@Med.ZAIRI 的回答发布在此线程上,每个未同步到MANAGER 1 MANAGER 2中的用户都可以看到MANAGER 1所有帖子

在模型类别中添加一个关系,例如:

/**
* this will get the parent category
*/
public function parentCategory()
{
    return $this->belongsTo( Category::class, 'category_id', 'id' );
}

然后,尝试获取具有类别和父类别的帖子,以及具有角色的用户,例如:

$posts = Post::with( ['category.parentCategory', 'user.roles'])->get()

我在这个场景中使用的模型:

class Category extends Model
{
    use SoftDeletes;

    protected $guarded = ['id'];
    protected $hidden = ['id', 'category_id'];

    public function parentCategory()
    {
        return $this->belongsTo( Category::class, 'category_id', 'id' );
    }

    public function categories()
    {
        return $this->hasMany(Category::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function childrenCategories()
    {
        return $this->hasMany(Category::class)->with('categories');
    }
}


class Role extends Model
{
    protected $guarded = ['id'];

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function permission()
    {
        return $this->belongsToMany(Permission::class);
    }

    public function hasPermission($permission)
    {
        return !!$permission->intersect($this->roles->permission)->count();
    }
}


class User extends Authenticatable
{
    use Notifiable, SoftDeletes, UsersOnlineTrait;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'avatar_path' => 'array',
        'experiences' => 'array',
    ];

    public function group()
    {
        return $this->belongsToMany(UserGroup::class, 'user_user_group');
    }

    public function child()
    {
        return $this->hasMany(User::class)->with('child');
    }

    public function parent()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function properties()
    {
        return $this->hasOne(UsersProperty::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function hasRole($role)
    {
        return $this->roles->contains('id', $role);
        /*if (is_string($role)) {
        } else {
            return !!$role->intersect($this->roles)->count();
        }*/
    }

    public function hasRoleByName($role)
    {
        if ($role == null) return false;
        if (is_string($role)) {
            return $this->roles->contains('name', $role) || $this->roles->contains('label', $role);
        } else {
            return !!$role->intersect($this->roles)->count();
        }
    }

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

}

在模型类别中添加一个关系,例如:

/**
* this will get the parent category
*/
public function parentCategory()
{
    return $this->belongsTo( Category::class, 'category_id', 'id' );
}

然后,尝试获取具有类别和父类别的帖子,以及具有角色的用户,例如:

$posts = Post::with( ['category.parentCategory', 'user.roles'])->get()

将此添加到您的角色模型中:

    public function categories()
    {
        return $this->hasMany(Category::class);
    }

之后,您可以访问用户的帖子,例如:

$authorizedUser->roles()->with('categories.posts')->get();

您也可以将结果展平以直接访问帖子

具有根据角色获取登录用户所有可用帖子的方法的特征

class User extends Model
{
    use HasFactory, Notifiable, HasPosts;
}



<?php

namespace App\Concerns;

use App\Models\Category;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;

trait HasPosts
{
    /**
     * Get all available posts for the currently logged in user
     *
     * @return void
     */
    public function posts()
    {
        $method = 'postsFor' . Str::studly(str_replace('is-', '', $this->roles->first()->label));

        return $this->{$method}()->collapse();
    }

    /**
     * Get all posts associated with all categories including
     * their subcategories for the logged in Portal Manager
     */
    public function postsForPortalManager(): Collection
    {
        return Category::with([
            'subcategories.posts.language', 
            'posts.language'
        ])
        ->get()
        ->pluck('posts');
    }

    /**
     * Get all posts for the logged in Manager which belong to
     * one of the categories associated with the Manager
     */
    public function postsForManager(): Collection
    {
        return $this->categories()
            ->with('posts.language')
            ->get()
            ->pluck('posts')
            ->filter(function ($collection) {
                return !!$collection->count();
            });
    }

    /**
     * Get only the posts which belong to the categories for the Editor
     * and which are authored by the logged in Editor
     */
    public function postsForEditor(): Collection
    {
        return $this->categories()
            ->with([
                'posts' => function ($query) {
                    $query->where('user_id', $this->id)->with('language');
                }, 
                'posts.language'
            ])
            ->get()
            ->pluck('posts')
            ->filter(function ($collection) {
                return !!$collection->count();
            });
    }

    /**
     * Get only the posts which belong to the categories for the Writer
     * and which are authored by the logged in Writer
     */
    public function postsForWriter(): Collection
    {
        return $this->categories()
            ->with([
                'posts' => function ($query) {
                    $query->where('user_id', $this->id)->with('language');
                }, 
                'posts.language'
            ])
            ->get()
            ->pluck('posts')
            ->filter(function ($collection) {
                return !!$collection->count();
            });
    }
}

然后对于任何经过身份验证的用户,我们可以获取可用的帖子

$user->posts()

它适用于您提供的种子数据。

ella 看不到 Flutter 上的帖子,而 Scarlett 看不到 Laravel 上的帖子

这里唯一的假设是已经采取了经过身份验证的用户的第一个角色来查找所使用的方法。

如果您的关系都是多对多的,如下所示:

roles >-< users >-< categories >-< posts

并且都在模型中正确定义,例如

// Role.php
public function users()
{
    return $this->belongsToMany(User::class);
}

// User.php
public function categories()
{
    return $this->belongsToMany(Category::class);
}

// Category.php
public function posts()
{
    return $this->belongsToMany(Post::class);
}

那么我很确定你应该能够做到

$role = Role::find(1);

// get all posts from all categories from all users with $role
$posts = $role->users()->categories()->posts;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM