Laravel 5 雄辩的 hasManyThrough/belongsToManyThrough 关系

dat*_*dan 5 php many-to-many laravel eloquent laravel-5

在 Laravel 5.2 应用程序中,我有三个模型:User,RoleTask. AUser与 multiple 相关联Roles,aRole与 multiple 相关联Tasks。因此,每个用户通过他们的角色与多个任务相关联。

我正在尝试通过他们的角色访问Tasks与 a 相关的所有内容User

我的模型的相关部分如下所示:

class User extends Authenticatable
{    
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function tasks()
    {
        return $this->hasManyThrough('App\Task', 'App\Role');
    }
}

class Role extends Model
{
    public function tasks()
    {
        return $this->belongsToMany('App\Task');
    }

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

class Task extends Model
{    
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    } 
}
Run Code Online (Sandbox Code Playgroud)

以下返回一个 SQL 错误;

Column not found: 1054 Unknown column 'roles.user_id'
Run Code Online (Sandbox Code Playgroud)

它似乎试图通过 Role 模型中的(不存在的)外键而不是通过数据透视表来访问关系。

$user = Auth::user;
$tasks = $user->tasks;
Run Code Online (Sandbox Code Playgroud)

如何通过这些关系访问与用户相关的所有任务?

小智 0

从您共享的源代码来看,您之间似乎存在Many to Many以下关系:UserRole之间以及Role和 之间Task

hasManyThrough方法需要两个One to Many关系。

User获取所有相关的可能方法Task是:(在User类内)

public function getTasksAttribute()
{
    $tasks = [];
    foreach ($this->roles as $role) {
        $tasks = array_merge($tasks, $role->tasks);
    }
    return $tasks;
 }
Run Code Online (Sandbox Code Playgroud)

然后,您将能够通过以下方式访问任务:

$user->tasks;
Run Code Online (Sandbox Code Playgroud)