Search code examples
mysqlcakephpselectmodelinsert

Cakephp insert into with select using model


Can I create this query in cakephp using model?

INSERT INTO table (name,age)
SELECT name, age
FROM table2
WHERE age >= 50

Solution

  • You have 2 options:

    The ugly one: Use Model::query. DO NOT USE THIS UNLESS IT IS ABSOLUTELY NECESSARY

    The decent one: (I am not going to give you a copy/paste solution, instead I will give you the idea)

    • Get all data from the model2 ($data = $Model2->find('all', array('conditions' => ...
    • Apply (if needed) some format to the variable that contains your results
    • Use Model::saveMany()