Wednesday, March 18, 2015

Re: Can't save associations CakePHP 3

just
if($this->data){
$project_id = $this->Projects->save($this->request->data);
}
you can get last inserted id and save it in projectImages table.


On Wednesday, 11 March 2015 14:21:23 UTC+5:30, ivan neykov wrote:

Hi,

I have two tables – Projects and ProjectsImages. When adding new project I want also to add one record in ProjectsImages with foreign key (project_id) equal to newly added project id. Values in other ProjectsImages fields must be default.

According documentation "When you are saving an entity, you can also elect to save some or all of the associated entities. By default all first level entities will be saved…", so I believe even don't need 'associated' option, but it doesn't work.

 

 

This is association for Projects table:

 

public function initialize(array $config) {

…..

        $this->hasMany('Images', [

            'className' => 'ProjectsImages',

            'foreignKey' => 'project_id',

            'dependent' => true

        ]);

…..

 

And this is add action in Projects controller:

 

    public function add() {

        $project = $this->Projects->newEntity();

        if ($this->request->is('post')) {

            //$this->request->data['images'] = [['parent_id' => null]];

            $project = $this->Projects->patchEntity($project, $this->request->data, ['associated' => ['Images']]);

            //$project->dirty('images', true);

            if ($this->Projects->save($project)) {

……

 

I tried variants with and without data['images'], and with and without dirty.

There are no errors, record in Projects table is ok, but no record in ProjectsImages.

The association is seems to be ok, because it's retrieves data with this:

$project = $this->Projects->get($id, ['contain' => ['Images']]);

 

I read related documentation couple times and can't figure out what is wrong.

 

Thanks

 

--
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: