mysql - 设置laravel Eloquent关系报错

标签 mysql laravel laravel-5 eloquent

我正在尝试使用 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/

相关文章:

MySQL根据日期和另一列的值更新一列的值以等于另一列的值的总和

php - 复制整个模型的数据库并插入到同一个表中并更改列

php - laravel 如何读取 app/config/app.php 调试变量

laravel - 在 Laravel 中获取用户名和带有文章 id 的评论

如果验证失败,Laravel 会预填多个表单

php - 找不到 Laravel 5 用户模型

php - 验证用户实例不工作 Laravel 5.0

mysql - 如何让多条记录加入一张表或使用contain with conditions?

mysql - 将 dd/mm/yyyy 字符串转换为 MySQL 中的 Unix 时间戳

mysql - 将某些字段(仅结构)从另一个表复制到现有表中