lasse
lasse

Reputation: 25

CakePHP: What is the correct format for saving data in a HABTM

I have an artist that has and belongs to many related artists, in this example i want to save Madonna and her 2 related artists Cher and Kylie Minogue in the database.

DB: 2 tables: artists (id, name, created) and artists_related (id, artist_id, related_id)

Model relationship setup:

<?php
class Artist extends AppModel {
    public $hasAndBelongsToMany = array(
        'Related' =>
            array(
                'className' => 'Artist',
                'joinTable' => 'artists_related',
                'associationForeignKey' => 'related_id',
                'unique' => 'keepExisting'
            )
        );

I'm trying to save the data like this:

    $test_data = array(
        'Artist' => array(
            'name' => 'Madonna'
         ),
        'Related' => array(
            0 => array(
                'name' => 'Kylie Minogue'
            ),
            1 => array(
                'name' => 'Cher'
            )
        )
    );

    $result = $this->saveAll($test_data, array('deep' => true));

What happens is that only Madonna is saved in the artists table, the two related artists arent saved, and nothing is saved in the join table.

How should the data array be formatted to accomplish this? Or do i need to save first Madonna, and get the id and then save all the related artists in a different saveAll() ?

Upvotes: 2

Views: 947

Answers (2)

Chanraksmey
Chanraksmey

Reputation: 126

As I know the related artist must contain Related Object that have key Related with some artist_id. This is example:

$test_data = array(
    'Artist' => array(
        'name' => 'Madonna'
     ),
    'Related' => array(
         'Related' => array(
             0 => '1',
             1 => '2'
         )
     )
);

Upvotes: 2

Colby Guyer
Colby Guyer

Reputation: 594

You data has to be in this format.

Array
(
[0] => Array
    (
        ['Artist'] => Array
            (
                [name] => 'Madonna'
            )
        ['Related'] => Array
            (
                [name] => 'Kylie Minogue'
            )
    )
[1] => Array
    (
        ['Artist'] => Array
            (
                [name] => 'Madonna'
            )
        ['Related'] => Array
            (
                [name] => 'Cher'
            )
    )
)

Upvotes: 0

Related Questions