【问题标题】:Multiple with() function in Laravel Query: Laravel 5.2.37Laravel 查询中的多个 with() 函数:Laravel 5.2.37
【发布时间】:2016-07-14 00:16:49
【问题描述】:

模型 1

class RoleModel extends Model {

    public $table = 'tblrole';
    public $primaryKey = 'RoleID';
    public $timestamps = true;

    public function RoleBasedPermissions() {
        return $this->hasMany('App\Models\Role\RolePermissionModel', 'RoleID', 'RoleID');
    }
}

模型 2

class RolePermissionModel extends Model
{
    public $table = 'tblrolepermission';
    public $primaryKey = 'RolePermissionID';
    public $timestamps = false;

    public function Permission() {
        return $this->hasOne('App\Models\Role\RolePermissionModel', 
            'PermissionID', 'PermissionID');
    }

    public function Role() {
        return $this->hasOne('App\Models\Role\RoleModel', 
            'RoleID', 'RoleID');
    }
}

模型 3

class PermissionModel extends Model
{
    public $table = 'tblpermission';
    public $primaryKey = 'PermissionID';
    public $timestamps = false;

    public function Module() {
        return $this->hasOne('App\Models\Role\ModuleModel', 
            'ModuleID', 'ModuleID');
    }

    public function Action() {
        return $this->hasOne('App\Models\Role\ActionModel', 
            'ActionID', 'ActionID');
    }
}

我的查询如下

$data = RoleModel
    ::where('RoleID', $RoleID)
    ->with('RoleBasedPermissions')
    ->with('RoleBasedPermissions.Permission')
    ->with('RoleBasedPermissions.Permission.Module')
    ->get();  

错误

调用未定义的方法 Illuminate\Database\Query\Builder::Module()

详情

问题出在这个查询部分->with('RoleBasedPermissions.Permission.Module')

我错过了什么吗?

【问题讨论】:

    标签: laravel laravel-5 laravel-5.1 laravel-5.2


    【解决方案1】:
    public function Permission()
    {
        return $this->hasOne(
            'App\Models\Role\PermissionModel', // <-- This is wrong in your code above
            'PermissionID',
            'PermissionID'
        );
    }
    

    另外,其他参数可能也需要更新。


    顺便说一句,您不需要对with 进行这 3 次调用。一次调用将加载整个链:

    $data = RoleModel::where('RoleID', $RoleID)
        ->with('RoleBasedPermissions.Permission.Module')
        ->get();
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2020-08-01
      • 2019-03-30
      • 2019-02-25
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多