cakephp 2.x how to save data in habtm join table only? - cakephp-2.0

I have a users and a posts table.
When I save the post it successfully saves it through HABTM (in posts_users table as well).
Now I want that post to be accessible to multiple user.
How can I add data in posts_users table alone so that post_id is now also associated with other user_id in the table users_posts ?
I have tried the following code:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('User.id',array('value'=>34));
echo $this->Form->input('Post.id',array('value'=>34));
echo $this->Form->end('Save Post');
?>

I think what you want is the unique HABTM key:
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id',
'associationForeignKey' => 'post_id',
'joinTable' => 'posts_users',
'unique' => 'keepExisting'
)
);

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.

An instance of a model cannot be created once relation has been added CakePHP

I have three models in question: Customer, Company and User. Customer and User both belong to Company and Company has many Customers as following:
Customer:
var $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id',
'dependent' => false,
),
);
Company:
var $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'company_id',
'dependent' => false
),
'Customer'=>array(
'className' => 'Customer',
'foreignKey' => 'company_id',
'dependent' => false
)
);
User:
var $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'company_id',
'dependent' => false,
),
);
I have a problem when creating/editing Customer objects. Here is how to create form looks like:
echo $this->Form->input('Customer.customer_nr');
echo $this->Form->input('Customer.name');
echo $this->Form->input('Customer.phone');
echo $this->Form->input('Customer.email');
echo $this->Form->input('Customer.address');
echo $this->Form->input('Customer.post_nr');
echo $this->Form->input('Customer.city');
echo $this->Form->input('Customer.company_id', array('value' => $current_user['company_id'], 'type'=>'hidden'));
What I do in the end of the form is I take company_id from a currently logged in user and insert it as a Customer.company_id. It used to work without any problems before the new relations have been introduced. But now as I try to create/edit Customer, I receive the following SQL error:
Error: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'name' in where clause is ambiguous
Any help is much much appreciated.
Here is the controller add function:
function add() {
if (!empty($this->data) ) {
$this->Customer->create();
if ($this->Customer->save($this->data)) {
$this->Session->setFlash(__('Customer was saved'), 'positive_notification');
$this->redirect(array('controller'=>'events', 'action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Customer has been saved. Please, try again'), 'negative_notification');
}
}
}
The error is definately not being cause by redirect as it was fully tested.
the problem is somewhere else.
It's in fact related to a find() call.
Try to locate the exact code that trigger the error and post it in your question.
Probably you set some conditions like
'conditions' => array(
'name' => 'john'
)
but you better do something like
'conditions' => array(
'User.name' => 'john'
)
after you created the relationship between User and Company (it's just an example, maybe the two tabler involved are others) Cake started to join the two tables. So when you search for a particular name mysql doesn't know if you want user name or company name because you have name column in both tables.
If you look at the generated query (the one that gives you that error) you'll see the two tables joined. If you don't want that join you have to specify recursive => -1
'conditions' => array(
'name' => 'john'
),
'recursive' => -1

Joins tables in Cakephp

i have a two tables namely; histories and users. i need to display data like:
id | Username | Lastest created Post | First created Post
the data of id and username is from users table and the last created and first created post data is from histories. i need to view all the users, their lastest created post and their first created post. please help me to make controller and view thanks
Try below.
<?php
$users = $this->User->find('all',array
(
'conditions' => array
(
//conditions goes here
),
'fields' => array
(
'User.id',
'User.username',
'History.Lastest created Post',
'History.First created Post'
)
));
?>
Assume that relation between 'User' and 'History' table is One-to-One and there's a 'user_id' column in History table, you may need to specify relation between them in History model, for example:
var $hasOne = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Then, you need to perform joins to do this. For example, somewhere in your User model, try something like this:
class User extends AppModel {
....
function getAllUsersHistory{
$allHistories = $this->find('all', array(
'joins' => array(
'table' => 'history',
'alias' => 'HistoryJoin'
'type' => 'INNER',
'conditions' => array(
// your conditions, for example: 'History.user_id' => 'User.id'
)
),
'fields' => array(
'User.id',
'User.username',
'History.lastest_created_post',
'History.first_created_post'
)
));
return $allHistories;
}
.....
}

Cakephp habtm relation updating instead of saving

Hello my problem is i try to save a new relation between a shop and a payment method
the relation is habtm... shop and payment already exist. i want to ad more payment methods.
But always when i save ,the old payment realtion in the shop_payment table is only updated, not a second one saved....
i read a lot i set unique to false but nothing changes that.
Anyone got an idea?
Model
class Payment extends AppModel {
var $hasAndBelongsToMany = array(
'Mainshop'=>array('className'=>'Mainshop', 'unique'=>'false')
);
}
View
echo $this->Form->create('Mainshop');
echo $this->Form->input('name',array('default'=>$mainshop['Mainshop']['name']));
echo $this->Form->input('Payment.id', array(
'type' => 'select',
'options' => array($payments),
));
echo $this->Form->input('id', array('type'=>'hidden','value'=>$mainshop['Mainshop'] ['id']));
echo $this->Form->end('Edit Shop');?>
Controller
if (!empty($this->data)){
$this->Mainshop->save($this->data);
$this->redirect(array('action' => 'edit',$this->data['Mainshop']['id']));
}
My recommendation defines the relationship with all fields in model:
var $hasAndBelongsToMany = array(
'Mainshop'=>array(
'className'=>'Mainshop',
'unique'=>'false',
'joinTable' => 'shop_payments',
'foreignKey' => 'payments_id',
'associationForeignKey' => 'shop_id'
)
);
In the controller add create():
if (!empty($this->data)){
$this->Mainshop->create();
$this->Mainshop->save($this->data);
$this->redirect(array('action' => 'edit',$this->data['Mainshop']['id']));
}

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