Laravel Query中的多个with()函数:Laravel 5.2.37

时间:2016-07-14 00:16:49

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

模型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')

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

public function Permission()
{
    return $this->hasOne(
        'App\Models\Role\PermissionModel', // <-- This is wrong in your code above
        'PermissionID',
        'PermissionID'
    );
}

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

顺便说一下,你不需要那3次拨打with。一次通话将加载整个链:

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