CakePHP : 1054 Unknown column 'User.id' in 'field list' - cakephp

I am learning CakePHP. There, I am stuck with following problem:
I have a table called comments with fields comment_id, comment_title, comment_text, comment_date & user_id.
Also I have my users table with fields user_id, user_name, user_email, created_date.
Then in my User model I am trying to create a hasMany relationship like :
var $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id'
), );
But this giving me an error
1054 Unknown column 'User.id' in 'field list'
I know this is because I don't have an id column in my users table instead I have user_id
Now, my question is : is there a way to fix this without renaming the user_id field of user table? As this will require change in every existing code where I have used user_id ?

Set in your User model:
public $primaryKey = 'user_id';
If you need create some relationship and models, controller, views.. You can use Bake shell, see: http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

To avoid this kind of errors use foreign key constraints in database.
Cakephp automatically add associations between tables.

public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'conditions' => array('Comment.user_id' => 'User.user_id'),
'dependent' => true
)
);

Related

Saving data with HABTM and HasMany looses foreignKey

I have a User model with two relations:
HasAndBelongsToMany
public $hasAndBelongsToMany = array(
'group' => array(
'className' => 'group',
'foreignKey' => 'user_id'
)
);
HasMany
public $hasMany = array(
'phonenumber' => array(
'className' => 'phonenumber',
'foreignKey' => 'user_id'
)
);
Phonenumber and Group have set
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
When I use
$this->saveAll(array(
'User' => $data,
'phonenumber' => $numbers, //array with data
'group' => $groups //array with data
)
);
The data gets saved in the tabels but User_id is "0" in phonenumber and group table.
How can I get the correct ID saved ? (CakePHP v 2.5)
FWIW saveAll() should work as advertised, populating the new user_id in the child tables in one fell swoop.
Have you paid attention to the relevant options: atomic & deep?
Especially if database does not support transactions, you'll need to pass in atomic:
$this->saveAll(array(
'User' => $data,
'phonenumber' => $numbers, //array with data
'group' => $groups //array with data
),
array('atomic' => false)
);
Considering the CakePHP documentation you will find this hint:
When working with associated models, it is important to realize that
saving model data should always be done by the corresponding CakePHP
model. If you are saving a new Post and its associated Comments, then
you would use both Post and Comment models during the save operation
(http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto)
Based on that information I suggest you try the following:
$this->User->save($data); // first save the user
Assuming you have multiple numbers:
foreach($numbers as $key => $nbr) {
// set user_id related data
$numbers[ $key ]['Phonenumber']['user_id'] = $this->User->id;
}
Finally save your related data:
$this->User->Phonenumber->saveAll($numbers);
Since this code is untested you may need to take some adjustments. Always ensure to follow the Cake-Conventions and use CamelCase ModelNames.

HABTM selection seemingly ignores joinTable

UPDATE #2 -- SOLUTION FOUND:
Turns out my use of this lookup:
$this->User->Group->find(....)
was not what I needed. To pull out a user's groups I needed to use:
$this->User->find('all',array('conditions' => array('User.id' => $user_id)));
< /UPDATE #2>< PROBLEM>
I'm attempting to do a HABTM relationship between a Users table and Groups table. The problem is, that I when I issue this call:
$this->User->Group->find('list');
The query that is issued is:
SELECT [Group].[id] AS [Group__id], [Group].[name] AS [Group__name] FROM [groups] AS [Group] WHERE 1 = 1
I can only assume at this point that I have defined my relationship wrong as I would expect behavior to use the groups_users table that is defined on the database as per convention. My relationships:
class User extends AppModel {
var $name = 'User';
//...snip...
var $hasAndBelongsToMany = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id',
'joinTable' => 'groups_users',
'unique' => true,
)
);
//...snip...
}
class Group extends AppModel {
var $name = 'Group';
var $hasAndBelongsToMany = array ( 'User' => array(
'className' => 'User',
'foreignKey' => 'group_id',
'associationForeignKey' => 'user_id',
'joinTable' => 'groups_users',
'unique' => true,
));
}
Is my understanding of HABTM wrong? How would I implement this Many to Many relationship where I can use CakePHP to query the groups_users table such that a list of groups the currently authenticated user is associated with is returned?
UPDATE
After applying the change suggested by ndm I still receive a large array return (Too big to post) which returns all groups and then a 'User' element if the user has membership to that group. I looked at the query CakePHP uses again:
SELECT
[User].[id] AS [User__id],
[User].[username] AS [User__username],
[User].[password] AS [User__password],
[User].[email] AS [User__email], CONVERT(VARCHAR(20),
[User].[created], 20) AS [User__created], CONVERT(VARCHAR(20),
[User].[modified], 20) AS [User__modified],
[User].[full_name] AS [User__full_name],
[User].[site] AS [User__site],
[GroupsUser].[user_id] AS [GroupsUser__user_id],
[GroupsUser].[group_id] AS [GroupsUser__group_id],
[GroupsUser].[id] AS [GroupsUser__id]
FROM
[users] AS [User] JOIN
[groups_users] AS [GroupsUser] ON (
[GroupsUser].[group_id] IN (1, 2, 3, 4, 5) AND
[GroupsUser].[user_id] = [User].[id]
)
Is there an easy way to refine that such that I only receive the group ids & names for the entries I have membership to? I was thinking of using:
array('conditions'=>array('GroupsUser.user_id'=>$user_id))
...but I receive an sql error on the groups table:
SELECT TOP 1 [Group].[name] AS [Group__name], CONVERT(VARCHAR(20), [Group].[created], 20) AS [Group__created], CONVERT(VARCHAR(20), [Group].[modified], 20) AS [Group__modified], [Group].[id] AS [Group__id] FROM [groups] AS [Group] WHERE [GroupsUser].[user_id] = 36 ORDER BY (SELECT NULL)
I think you just misunderstood what the list find type is ment to do.
The query is totally fine, the list find type is used for retreiving a list of records of a single model only, where the models primary key is used as index, and the display field as value.
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list

Join two tables using specified fields in CakePHP

I have two tables called Siteaddress and Jobsheet. In the Jobsheet table there is a field called siteaddress that contains the ID of the site address stored in the Siteaddress table.
The problem I am having is that while I'm doing the join in the controller, CakePHP is joining the Siteaddress table to the Jobsheet table using the id fields in both tables. This causes a problem as there is only one record (so far) in the Siteaddress table, and multiple records in the Jobsheet table.
What I need to do is tell CakePHP to join Jobsheet.siteaddress to Siteaddress.id instead of the way it's working at the moment.
How am I able to do this?
Below is the relationship code from the Jobsheet model file:
public $hasOne = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Siteaddress' => array(
'className' => 'Siteaddress',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Cheers!
You've set the foreignKey to id so Cake uses this for making the join. This key can be set to any table field you want in the table you want joined. If I understand you correctly you should set the foreignKey to siteaddress:
'Siteaddress' => array(
'className' => 'Siteaddress',
'foreignKey' => 'siteaddress',
'conditions' => '',
'fields' => '',
'order' => ''
)
See the manual entry for hasOne as well.
EDIT:
In this case $belongsTo might be a better fit as an association.

Cake PHP foreignkey issues

So I am using cakephp and I am a little new to this and I am facing certain issues.
1) I have two tables, report and issues.
cakephp:
report{id, type, details}
issue{id,report_id, details}
So now I am trying to get the report id in issues table. I have defined my hasmany and belongsto relationships as follows:
class Report extends AppModel {
var $name = 'Report';
var $hasMany = array(
'AtneIssue' => array(
'className' => 'Issue',
'foreignKey' => 'report_id',
'dependent' => true,
)
);
}
class Issue extends AppModel {
var $name = 'Issue';
var $belongsTo = array(
'Report' => array(
'className' => 'Report',
'foreignKey' => 'report_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
But this results in a sql error and the data not being saved to the table. I have set index to report_id to get id from Report.
Data is getting saved to reports but not to issues table.
Can someone tell me how to go about this?
Thanks in advance.
The first letter is replace by number here. dunno why... I figured how to post data But now I am not able to get the ID of the report and the data is getting corrupted like below:
Query: INSERT INTO `atne_issues` (`status`, `issue_owner`, `issue_reason`, `problem`) VALUES ('2nhold', '2ricsson', '2IQ - IP address incorrect', '2sdfasdf')

How do I link one table two times to another table using cakePHP

I'm trying to set up a social networking type of site, where users can have friends and send each other messages.
I have a users table, and a friends table, which basically has an user_id and user_friends_id.
Using cakePHP, how can I link the user_id and user_friend_id back to the users table?
I used bake to create all my models and controllers, but when I viewed the users page, I got an error because cakePHP doesn't know how to link the user_friend_id back to the users table.
Can anyone please help?
table names (fields):
users (user_id, user fields....)
friends_users (user_id, friend_id)
associations:
User hasAndBelongsToMany Friend
Friend hasAndBelongsToMany User
in User model:
var $hasAndBelongsToMany = array(
'Friend' => array(
'className' => 'User',
'joinTable' => 'friends_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
);
in Friend model:
var $useTable = 'users';
var $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'friends_users',
'foreignKey' => 'friend_id',
'associationForeignKey' => 'user_id',
);

Resources