属于许多获得所有行(Laravel) [英] Belongs to many get all rows (Laravel)

查看:69
本文介绍了属于许多获得所有行(Laravel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模型和一个属性模型.用户具有3个角色:管理员,经理和代理.管理员可以查看所有属性,而经理和经纪人只能查看分配给他们的属性.经理或经纪人可能具有许多财产,而财产可能属于任何数量的经理和经纪人.这是我的用户模型中的properties关系:

I have a User model and a Property model. The user has 3 roles: admin, manager, and broker. The admins can view all properties, while the managers and brokers can only view the properties that are assigned to them. A manager or broker may have many properties and a property may belong to any number of managers and brokers. Here is the properties relationship in my User model:

/**
 * Get all properties belonging to this user.
 *
 * @return [type]            [description]
 */
public function properties()
{
    if ($this->isAdmin()) {
        return Property::all();

    } elseif ($this->isManager() || $this->isBroker()) {
        return $this->belongsToMany('App\Property');

    }

    return null;
}

这对于检索所有属性非常有用,但是如果我必须执行select或where语句,则只能在用户不是的情况下执行此操作,因为当前代码将返回整个Collection如果用户是管理员.这样就不可能将这种方法用于搜索功能和任何类型的约束.

This works great for retrieving all properties, but if I have to perform select or where statements, I can only do so if the user is not an admin, since the current code returns the entire Collection if the user is an admin. This makes it impossible to use this method for search functionality and any type of constraint.

很显然,我不想在property_user表中为每个单个属性和admin创建一条记录,因为那样会占用很多不必要的空间.但是,我不希望控制器中具有其他逻辑,以仅在用户是经理或经纪人的情况下调用properties方法,而在用户是管理员的情况下执行自定义查询.

Obviously, I do not want to create a record in the property_user table for every single property and admin, as that would take up loads of unnecessary space. However, I do not want to have additional logic in my controllers to only call the properties method if the user is a manager or broker, and perform a custom query if the user is an admin.

有什么办法可以返回其中包含每一行的Illuminate\Database\Eloquent\Relations\BelongsToMany吗?还是我仍然可以将查询链接到的另一个Laravel对象?

Is there any way I can return an Illuminate\Database\Eloquent\Relations\BelongsToMany that has every row in it? Or another Laravel object that I can still chain queries to?

推荐答案

您将要返回查询对象.

public function properties()
{
    if ($this->isAdmin()) {
        return Property::query();
    } elseif ($this->isManager() || $this->isBroker()) {
        return $this->belongsToMany('App\Property');
    }

    return null;
}

这篇关于属于许多获得所有行(Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆