Why does saveAll () save only the last record?

I have a situation where, for external reasons, I have to directly save the union records, and not save them as part of the connection. Here is what I mean:

  • I have a Firm model whose data is extracted from an external source.
  • I have a County model in my application database
  • I have a counties_firms join table that I use to associate these external firms with counties.

Due to the fact that he lives there, I do not edit the Firm model and I do not edit the County model. I just edit the associations. I have a Firm model for encapsulating everything that I need to do with company data, and one of these methods is Firm::saveCounties( $data ) . It:

  • Accepts incoming data containing the company identifier and county identifiers that must be associated.
  • Deletes all existing connection records for this county.
  • Trying to save all new connection records.

I find that only the last county record is saved. Here is the input:

 Array ( [0] => Array ( [firm_id] => 13 [county_id] => 4fa16e24-a25c-4523-8a9e-7d1d147402e8 ) [1] => Array ( [firm_id] => 13 [county_id] => 4fa16e27-ccd0-4f22-97da-7d1d147402e8 ) [2] => Array ( [firm_id] => 13 [county_id] => 4fa16e4a-68f8-4fb1-95bb-7d1d147402e8 ) ) 

Given this data, I create an on-the-fly relationship between Firm and CountiesFirm and try $this->CountiesFirm->saveAll( $data ) .

As I mentioned, only the last of the 3 county associations in this example is saved. Any idea what I might lose?

Thanks.

+4
source share
2 answers

I believe that you are missing a level in your array ... it should look something like this ...

 Array( 'CountiesFirm' => array( [0] => Array ( [firm_id] => 13 [county_id] => 4fa16e24-a25c-4523-8a9e-7d1d147402e8 ) [1] => Array ( [firm_id] => 13 [county_id] => 4fa16e27-ccd0-4f22-97da-7d1d147402e8 ) [2] => Array ( [firm_id] => 13 [county_id] => 4fa16e4a-68f8-4fb1-95bb-7d1d147402e8 ) ) ) 

Try it and let me know the results.

0
source

Your array is fine. It seems that the model does not clear its identifier, you can try and add ['id'] => null to each record in your array to force clear the model identifier.

It worked for me.

+2
source

Source: https://habr.com/ru/post/1414386/


All Articles