简体   繁体   中英

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

So I have two models, Post and Event. Both "haveAndBelongToMany" with each other.

In the Post.php model file I have this:

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:

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.

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? 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.

class Post extends AppModel {

    public $hasAndBelongsToMany = array(
        "Event"
    );

}

Then for saving the data from the controller you only need save($post_data).

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

Tested with CakePHP 2.6.0 and CakePHP 2.3.4.

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.

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