0

I am currently trying to figure out how to save a indexed array to a field in my database. That said, I know an array can't be saved to a database, but you can serialize it or implode it and then save. Im not sure which one I should be using though. I don't want a collection of items to be saved in just one cell. I need the list of items to be saved one by one in the column. So my question is do I need to be using the serialize method, implode or something else? Here is a glimpse of my code and the array I am trying to save.

 public function findPolicyIds($coverageId = null) {
    $policyid = $this->Policy->find('all', array(
        'recursive' => -1,
        'conditions' => array('Policy.coverage_id' => $coverageId),
        'fields' => array('Policy.id')));

        foreach($policyid as $id) {
            $all[] = $id['Policy']['id'];




        }
        return $all;
}


 Array
(
[0] => 5202834f-111c-4a76-8b33-1ed8ae78509d
[1] => 5202834f-2ba8-4957-91db-1ed8ae78509d
[2] => 5202834f-356c-49a1-beeb-1ed8ae78509d
[3] => 5202834f-3b40-453f-a491-1ed8ae78509d
Dave
  • 28,833
  • 23
  • 113
  • 183
SkillSet
  • 621
  • 2
  • 7
  • 15

1 Answers1

1

It depends.

This is probably the best answer to give you.

Do whatever you like, as long as it doesn't magically corrupt the data between write and read.

Lemme take a moment to explore a few options on your behalf.

  • var_export() - might not be the best idea, securitywise
  • serialize() - seems straightforward
  • implode() - seems straightforward
  • json_encode() - seems straightforward

There are probably other, more obscure, options available. You could even build up complex data sets with XML, if you like.

Alternatively, why not normalize the schema and add a new table to present that collections of array-data ? Normalization tends to save your bacon in the future.

starlocke
  • 3,407
  • 2
  • 25
  • 38
  • 1
    Adding the new table and a `hasMany()` relationship on your original table is the most cake-safe way to do it. – Derek Aug 07 '13 at 18:25
  • I can't add another table. The reason being is because of the relationships I already have in place. I need to save those ids into another table, which PolicyId is the foreign key. – SkillSet Aug 07 '13 at 19:27