I am facing a problem in CakePHP. I want hasAndBelongsToMany relationship to bs_categories
and bs_listing_types
tables. ( A category can have multiple listing types).
These are the table structure that i have used.
bs_categories
-------------
id int(10)
parent_id int(10)
lft int(10)
rght int(10)
title varchar(255)
body text
meta_title varchar(255)
meta_keyword text
meta_desc text
slug varchar(255)
status int(1)
created datetime
modified datetime
bs_listing_types
-----------------
id int(11)
title varchar(255)
status int(1)
created datetime
modified datetime
bs_listing_types_categories
---------------------------
id int(11)
listing_type_id int(11)
category_id int(11)
I have written following code in the model:
/**
* hasAndBelongsToMany associations
*
* @var array
*/
public $hasAndBelongsToMany = array(
'ListingType' => array(
'className' => 'ListingType',
'joinTable' => 'listing_types_categories',
'foreignKey' => 'listing_type_id',
'associationForeignKey' => 'category_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
At time of saving, i am getting following data.
Array(
[Category] => Array
(
[listing_type_id] => Array
(
[0] => 2
[1] => 3
)
[parent_id] =>
[id] => 1
[title] => Advert
[meta_title] => Advert
[meta_keyword] => Advert
[meta_desc] => Advert
[status] => 1
))
But the problem is that it is not saving the data into the bs_listing_types_categories
table. Am i doing anything wrong. Please HELP!
HABTM NEVER has ID column as per cakePHP convention else ,data wont save.
bs_listing_types_categories
Will have following fields only
listing_type_id int(11)
category_id int(11)
For more information LINK
For Example If posts are related to tags in HABTM , then ,check out posts_to_tags
Without id field.
CREATE TABLE `posts` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`body` text NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tags` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `posts_tags` (
`post_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`post_id`,`tag_id`)
);
Your table structure
your array should be like this so u should make the array like this before applying save using foreach loop.
Array(
[Category] => Array
(
[listing_type_id] => Array
(
[0] => 2
)
[listing_type_id] => Array
(
[1] => 3
)
[parent_id] =>
[id] => 1
[title] => Advert
[meta_title] => Advert
[meta_keyword] => Advert
[meta_desc] => Advert
[status] => 1
))
and while saving you should use saveAssociated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.