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

Multiple with() function in Laravel Query: Laravel 5.2.37

模型 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();  

错误

Call to undefined method Illuminate\Database\Query\Builder::Module()

详情

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

我是不是漏掉了什么?

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();