Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is saveAll() only saving the last record?

I have a situation where, for external reasons, I have to directly save join records rather than saving them as part of a join. Here's what I mean:

  • I have a Firm model whose data is pulled from an external source.
  • I have a County model in my app database
  • I have a counties_firms join table that I use to associate those external firms to counties.

Because of what lives where, I'm not editing a Firm model nor am I editing a County model. I'm really just editing the associations. I have a Firm model to encapsulate anything I need to do with Firm data and one of these methods is Firm::saveCounties( $data ). It:

  • Accepts incoming data that includes the firm id and the county ids that should be associated.
  • Deletes all existing join records for that county
  • Attempts to save all of the new join records.

What I'm finding is that only the last county record is saved. Here's the incoming data:

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 that data, I'm creating an on-the-fly association between Firm and CountiesFirm and attempting to $this->CountiesFirm->saveAll( $data ).

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

Thanks.

like image 367
Rob Wilkerson Avatar asked Oct 08 '22 17:10

Rob Wilkerson


1 Answers

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

This worked for me.

like image 125
Stefan van Gastel Avatar answered Oct 12 '22 12:10

Stefan van Gastel