0

I'm trying to insert an array element which contains an id for relational data inside an array save multiple records in CakePHP.

This is how the array appears:

[Venue] => Array (
    [0] => Array (
        [name] => Great mansion
        [where] => New York
    )
    [1] => Array (
        [name] => Diamond palace
        [where] => London
    )
    [2] => Array (
        [name] => Palazzo Falcone
        [where] => Bologna
    )
)

I would like to add the architect_id to every element of the array, so:

[Venue] => Array (
    [0] => Array (
        [name] => Great mansion
        [where] => New York
        [architect_id] => 33
    )
    [1] => Array (
        [name] => Diamond palace
        [where] => London
        [architect_id] => 33
    )
    [2] => Array (
        [name] => Palazzo Falcone
        [where] => Bologna
        [architect_id] => 33
    )
)

I'm not sure if what I've wrote is optimized or it can be improved:

$tot = count($this->request->data['Venue']);

for ($i = 0; $i < $tot; $i ++) {
    $this->request->data['Venue'][$i]['architect_id'] = $this->Architect->id;
}

$this->Venue->saveAll($this->request->data['Venue']);

The code works but is this a good way to do that?

1 Answer 1

1

Your solution is fine so far.

foreach ($this->request->data['Venue'] as &$venue) {
  $venue['architect_id'] = $this->Architect->id;
}

Should work too. Decide yourself, which one you find more readable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.