【问题标题】:Laravel - Filter rows from model by function of another modelLaravel - 通过另一个模型的功能从模型中过滤行
【发布时间】:2019-08-07 20:31:58
【问题描述】:

我有一个项目模型和用户模型。 在用户模型中有一个检查用户是否有权限的功能:

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public function hasPermission($permission){
        $code = Permission::where('name',$permission)->first()->id-1;
        $total = $this->group->permissions;
        return ($total & pow(2,$code));
    }
}

我正在尝试通过此功能过滤项目,例如:

Items::where('sell_price','>',0)->where('user.hasPermission','SellItems');

items 模型如下所示:

class Items extends Model
{

    public function user(){
        return $this->belongsTo('App\User');
    }
}

【问题讨论】:

    标签: mysql laravel model


    【解决方案1】:

    hasPermission 在其当前状态下是一个需要获取模型才能工作的函数,因此不能真正用作查询。

    但是,您可以尝试在 SQL 中编写逻辑并在 whereHas 中使用它:

    Items::where('sell_price','>',0)->whereHas('user', function ($query) {
        $query->join('permissions', \DB::raw('users.group|(permissions.id-1)'), '!=', '0')
               ->where('permission.name', 'SellItems');
    });
    

    这有望获得与具有销售权限的用户关联的所有项目。

    【讨论】:

      【解决方案2】:

      您好,我认为您正在寻找 whereHas 方法: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

      这应该可以让您启动并运行!

      cmets 中提到的示例(请注意,没有对此进行测试):

      Item::whereHas('user', function($q) use ($permission) {
          //your permission query here you can use $permission;
      }
      

      【讨论】:

      • 这不完全是我需要在函数中插入参数
      • 为什么不能在闭包内使用变量。只需使用“使用”传递它们。我将在上面添加一个示例
      猜你喜欢
      • 2015-02-12
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2016-05-04
      相关资源
      最近更新 更多