简体   繁体   English

CakePHP-无法获取HABTM数据以保存新记录

[英]CakePHP - Can't get HABTM data to save with new record

So I have two models, Post and Event. 所以我有两个模型,Post和Event。 Both "haveAndBelongToMany" with each other. 两者“ haveAndBelongToMany”相互之间。

In the Post.php model file I have this: 在Post.php模型文件中,我有以下内容:

public $hasAndBelongsToMany = array(
    "Events"=>array(
        "className"=>"Event",
        "joinTable"=>"events_posts",
        "foreignKey"=>"post_id",
        "associationForeignKey"=>"event_id",
        "unique"=>true
    )
);

In the Event.php model file, I have this: 在Event.php模型文件中,我有这个:

public $hasAndBelongsToMany = array(
        "Posts"=>array(
            "className"=>"Post",
            "joinTable"=>"events_posts",
            "foreignKey"=>"event_id",
            "associationForeignKey"=>"post_id",
            "unique"=>true
        )
    );

My database has a table called "events_posts" with the two fields: post_id, event_id. 我的数据库有一个名为“ events_posts”的表,其中包含两个字段:post_id,event_id。

Now, in a different controller where I need to manually save info (not through a form) I have this chunk of code: 现在,在需要手动保存信息(而不是通过表单)的其他控制器中,我具有以下代码块:

$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)); 

It's saving the new post data, but not saving the relation into the events_posts table... Can someone please tell me what I'm doing wrong? 它正在保存新的帖子数据,但没有将关系保存到events_posts表中。有人可以告诉我我做错了什么吗? This is driving me absolutely insane. 这真让我发疯。

Use the singularize model name for associations. 将单数化的模型名称用于关联。 Follow the Model and Database Conventions and add the following code in your Post model. 遵循模型和数据库约定,并在Post模型中添加以下代码。

class Post extends AppModel {

    public $hasAndBelongsToMany = array(
        "Event"
    );

}

Then for saving the data from the controller you only need save($post_data). 然后,为了从控制器保存数据,您只需要save($ post_data)。

$result = $this->Post->save($post_data);

Tested with CakePHP 2.6.0 and CakePHP 2.3.4. 使用CakePHP 2.6.0和CakePHP 2.3.4进行了测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM