简体   繁体   English

在Laravel的Eloquent ORM中使用查找表:不是唯一的表别名?

[英]Using a lookup table with Laravel's Eloquent ORM: not unique table alias?

I've been trying to use Eloquent for an application I'm making (being proted from Codeigniter) but I can't get it to work. 我一直在尝试将Eloquent用于我正在制作的应用程序(已从Codeigniter进行验证),但我无法使其正常工作。

I have 3 tables: 我有3张桌子:

  • users
  • departments
  • department_members (this is the lookup table) department_members (这是查找表)

department_members has 3 fields: id, department_id and user_id. department_members具有3个字段:id,department_id和user_id。 All my tables have their own models. 我所有的表都有自己的模型。 When I try to use the ORM to get the department of an user ( User::find(1)->member()->first() ) all I get is this error: 当我尝试使用ORM获取用户的部门时( User::find(1)->member()->first() ),我得到的只是以下错误:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users' SQLSTATE [42000]:语法错误或访问冲突:1066不是唯一的表/别名:'users'

Although I know what the problem is, I don't know how to solve it, since it's all generated by the ORM. 尽管我知道问题是什么,但我不知道如何解决它,因为这都是由ORM产生的。

The models: 型号:

  • Member model 会员模型

     class Member extends Eloquent { public static $table = 'department_members'; public static $timestamps = false; public function user() { return $this->has_many_and_belongs_to('User', 'users'); } } 
  • User model 用户模型

     class User extends Eloquent { public static $timestamps = false; public function member() { return $this->has_many_and_belongs_to('Member', 'department_members'); } } 
  • Department model 部门模式

     class Department extends Eloquent { public function member() { return $this->has_many_and_belongs_to('Member', 'department_members'); } } 

The columns have appropiate names: id as PK, and the respective names with _id appended. 这些列具有适当的名称:id为PK,并在各个名称后附加_id。

If more info is needed I would be happy to help out. 如果需要更多信息,我将很乐意为您提供帮助。

You've setup your relationships incorrectly. 您的关系设置不正确。 You don't need to have a member model - just a User, and Department model. 您不需要成员模型-只需一个用户模型和部门模型。

Like so: 像这样:

# in User
public function departments() {
    return $this->has_many_and_belongs_to('Department', 'department_members');
}

# in Department
public function users() {
    return $this->has_many_and_belongs_to('User', 'department_members');
}

There's no need for the additional model. 不需要其他模型。 Additionally, you might want to read here: http://laravel.com/docs/database/eloquent#many-to-many - of special note is the pivot tables, in case you want to do some extra work on the join table aspect of the relationship. 此外,您可能需要在这里阅读: http : //laravel.com/docs/database/eloquent#many-to-many-特别要注意的是数据透视表,以防您想对联接表做一些额外的工作关系的方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM