HasMany in Cake PHP not working

I have a table called group_joins: Fields for the table above, like,

1)id, 2)group_id, 3)user_id, 4)created 

And two more tables - these are users and user_groups, group_id a link to the primary key of the user_groups table and a user_id link to the primary key of the user table.

Now I have created a model called GroupJoin, and I want to link the table above the two tables (users, user_groups) with group_joins so that I can get all the users who joined this group.

I pass group_id to the action as a parameter. And I need all users to belong to this group.

My model is as follows:

 var $belongsTo = array( 'UserGroup' => array( 'className' => 'UserGroup', 'foreignKey' => 'group_id' ) ); var $hasMany = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', 'conditions' => '', ) ); 

And in my controller, the query looks like this:

 $groupArrs = $this->GroupJoin->find('all',array('conditions'=>'GroupJoin.group_id ="'. $group_id.'"')); 

but it shows an SQL error: 1054: Unknown column "User.user_id" in the "list of fields"

then how can I get all the users that belong to this group.

+4
source share
3 answers

At first, your connection table name does not comply with CakePHP conventions. These should be group_users (the model name for this: GroupsUser), not groups_join or any other table name. See also this page .

Your associations should be:

  • User hasAndBelongsToMany UsersGroup
  • UsersGroup belongs to the user
  • User group belongs to user group.

When a user can ONLY belong to one user group, you don’t need a connection table at all. If you try the same query (UsersGroup.group_id => $ groupId), it should work.

Also, you disagree with the conventions for variable names in CakePHP: it should be $ groupId, not $ group_id. And use the right visibility keywords instead of "var".

0
source

Create user_id as a foreign key with a user table in your database.

0
source

I think it's better to follow the example of a bourzum.

Your models will look like this:

 class User extends AppModel{ public $hasMany = array( 'UserGroup' => array( 'className' => 'UserGroup', 'foreignKey' => 'user_id' ) ); } class Group extends AppModel{ public $hasMany = array( 'UserGroup' => array( 'className' => 'UserGroup', 'foreignKey' => 'group_id' ) ); } class UserGroup extends AppModel{ public $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', ), 'Group' => array( 'className' => 'Group', 'foreignKey' => 'group_id' ) ); } 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1490240/


All Articles