Sunday, January 11, 2015

Re: Can't seem to get simple HABTM to save...

Hi Jake

Does your events_posts table have a primary key, that is a column named id used for the primary key?
If not, then please add such and try again :)

Enjoy, John

On Sunday, 11 January 2015 16:45:30 UTC+2, Jake Newsom wrote:
So I have 2 models, Posts and Events.

Model Post.php looks like this: 
<?php
App::uses('AppModel','Model');

class Post extends AppModel{

...took out variables for brevity sake

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

Model Event.php has this: 
    public $hasAndBelongsToMany = array(
            "Posts"=>array(
                "className"=>"Post",
                "joinTable"=>"events_posts",
                "foreignKey"=>"event_id",
                "associationForeignKey"=>"post_id",
                "unique"=>true
            )
        );


In the database there's a table called events_posts with 2 fields: event_id & post_id

And finally, in a different controller, where I need to manually save stuff.... I have this 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(
                                "id"=>$event['Event']['id']
                            )
                        );

                    $this->Post->saveAll($post_data); 

And I've tried saveAll, save, and saveAssociated. The Post information saves, but nothing shows up in the events_posts table. What am I doing wrong? I'm sure it's gotta be some kind of alias mistake...

Thanks in advance for taking the time to read and help me!

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: