我正在尝试使用 Eloquent 关系模型在 Laravel 中建立关系,如下所示
users
id
email
projects
id
name
user_projects
user_id
project_id
role
我希望能够查询用户参与的项目,而不管他拥有什么角色。为此,我在我的用户模型中使用了以下内容。
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\ProjectRoles', 'user_projects', 'user_id', 'project_id');
}
}
但是正因为如此,我的代码出现了错误
Syntax error or access violation: 1066 Not unique table/alias: 'user_projects' (SQL: select `user_projects`.*, `user_projects`.`user_id` as `pivot_user_id`, `user_projects`.`project_id` as `pivot_project_id` from `user_projects` inner join `user_projects` on `user_projects`.`id` = `user_projects`.`project_id` where `user_projects`.`user_id` = 2)
我不确定如何在关系中创建连接查询才能执行此操作。任何帮助,将不胜感激。我浏览了 Eloquent 文档,但即使那里的示例完全符合我的要求,也无法获得结果。
最佳答案
您的 belongsToMany
关系与错误的模型相关。通常您的数据透视表没有模型,但即使您有,您的 belongsToMany
关系也不会使用它。您的 User
模型应该与您的 Project
模型相关。
你应该使用这个:
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\Project', 'user_projects', 'user_id', 'project_id');
}
}
关于mysql - 设置laravel Eloquent关系报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388705/