Вопрос

In my app, Users HABTM Solicitations.

After saving the form using $this->Solicitation->save($this->request->data), I need to add another user_id value in the solicitations_users table.

$data[] = array('User' => array('id' => 5), 'Solicitation' => array('id' => 77));
$data[] = array('User' => array('id' => 6), 'Solicitation' => array('id' => 77));

  $this->Solicitation->saveMany($data);

My $datais this:

array(
'User' => array(
    'id' => (int) 6
),
'Solicitation' => array(
    'id' => '54'
)
)

I need to save the association in the form and then add the new record above to the solicitations_users table as well. It's only saving the 6 and not the data from the form. It just saves the form if I delete the second save.

I realized that in the DB, this is jumping one id. This should be 'id' 36 => 5; 'id' 37 => 6. It looks like that is updating the table.

Here is the query:

enter image description here

Это было полезно?

Решение 5

Thanks guys.

But, based on this answer : CakePHP: Creating new HABTM row instead updates other

I found that instead of SaveAll create a new row, It update that already exists with new records. Because of this, i'v used query() to add a new row.

$this->Solicitation->query("INSERT INTO `contratos`.`solicitation_users` (user_id,solicitation_id) values($id, $solicitation");

Thanks for all

Другие советы

What is your posted data structure like?

According to the cookbook it should be

Array(
    'User' => Array(
        'id' => 6
    ),
    'Solicitation' => Array(
        'title' => 'A request'
    )
)

Give one of these two a shot:

$data[] = array('User' => array('id' => 5), 'Solicitation' => array('id' => 77));
$data[] = array('User' => array('id' => 6), 'Solicitation' => array('id' => 77));

$this->Solicitation->saveMany($data, array('deep' => true));

OR

$data[] = array('SolicitationsUser' => array('User.id' => 5,'Solicitation.id' => 77));
$data[] = array('SolicitationsUser' => array('User.id' => 6,'Solicitation.id' => 77));

$this->Solicitation->saveMany($data);

I think the easiest way is to use foreach. Like-

$data[] = array('User' => array('id' => 5), 'Solicitation' => array('id' => 77));
$data[] = array('User' => array('id' => 6), 'Solicitation' => array('id' => 77));

foreach($data as $da){
  $this->Solicitation->saveMany($da);
}

When you save an habtm relationship cake delete all the records relative to thet item and rewrite just the ones you are saving.

see the manual about it

So you have to save all your records at the same time providing an array like:

try

$data = array(
    'Solicitation' => array('id' => 77),
    'User' => array(
        'User' => array(6, 7)
    )
);

$this->Solicitation->saveAll($data);

you can also set 'unique' =>'keepExisting' in your habtm association array

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top