[英]CakePHP - Can't get HABTM data to save with new record
所以我有两个模型,Post和Event。 两者“ haveAndBelongToMany”相互之间。
在Post.php模型文件中,我有以下内容:
public $hasAndBelongsToMany = array(
"Events"=>array(
"className"=>"Event",
"joinTable"=>"events_posts",
"foreignKey"=>"post_id",
"associationForeignKey"=>"event_id",
"unique"=>true
)
);
在Event.php模型文件中,我有这个:
public $hasAndBelongsToMany = array(
"Posts"=>array(
"className"=>"Post",
"joinTable"=>"events_posts",
"foreignKey"=>"event_id",
"associationForeignKey"=>"post_id",
"unique"=>true
)
);
我的数据库有一个名为“ events_posts”的表,其中包含两个字段:post_id,event_id。
现在,在需要手动保存信息(而不是通过表单)的其他控制器中,我具有以下代码块:
$post_data = array(
"Post"=>array(
"image_id"=>$entry['id'],
"image_url"=>$entry['images']['standard_resolution']['url'],
"image_thumb"=>$entry['images']['low_resolution']['url'],
"image_text"=>$entry['caption']['text'],
"status"=>'1',
"created_on"=>$entry['created_time'],
"instagram_user_id"=>$user_id
),
"Event"=>array(
"Event"=>array($event['Event']['id'])
)
);
$result = $this->Post->save($post_data,array('deep' => true));
它正在保存新的帖子数据,但没有将关系保存到events_posts表中。有人可以告诉我我做错了什么吗? 这真让我发疯。
将单数化的模型名称用于关联。 遵循模型和数据库约定,并在Post模型中添加以下代码。
class Post extends AppModel {
public $hasAndBelongsToMany = array(
"Event"
);
}
然后,为了从控制器保存数据,您只需要save($ post_data)。
$result = $this->Post->save($post_data);
使用CakePHP 2.6.0和CakePHP 2.3.4进行了测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.