php - updateAll with relationships in CakePHP 2

415

I try update all Orders in the system, but have a "where" condition. How can I do that in CakePHP 2.3?

// OrderFood.php (Model)
$orderFood = $this->updateAll(
    array(
        'OrderFood.price' => 'OrderFood.original_price',
        'OrderFood.discount_percent' => 0,
        'OrderFood.discount_amount' => 0,
    ),
    array(
        'Order.check_num' => $check_num
    )
);

// OrderFood.php (Model)
/**
 * belongsTo associations
 *
 * @var array
 */
public $belongsTo = array(
    'Order' => array(
        'className' => 'Order',
        'foreignKey' => 'order_num',
    ),
    'Food' => array(
        'className' => 'Food',
        'foreignKey' => 'food_num'
    )
);

// Order.php (Model)
/**
 * hasMany associations
 *
 * @var array
 */
public $hasMany = array(
    'OrderDrink' => array(
        'className' => 'OrderDrink',
        'foreignKey' => 'order_num'
    ),
    'OrderFood' => array(
        'className' => 'OrderFood',
        'foreignKey' => 'order_num'
    )
);

When I try do that, Cake return this error message:

Error: SQLSTATE[42P01]: Undefined table: 7 ERRO: faltando entrada para tabela "Order" na cláusula FROM LINE 1: ...ROM "public"."order_foods" AS "OrderFood" WHERE "Order"."c... ^

SQL Query: SELECT "OrderFood"."order_num" AS "OrderFood__order_num" FROM "public"."order_foods" AS "OrderFood" WHERE "Order"."check_num" = 358171

Notice: If you want to customize this error message, create app\View\Errors\pdo_error.ctp
65

Answer

Solution:

You are trying to update yourOrderFood model but you are passing in a condition for theOrder model. If you look at the SQL error your WHERE clause is referencing theOrder table which was not been included in the statement.

I'm sure there is a better way to do this but one simple solution would be to query the Order table first and get theorder_num for yourcheck_num. Then change the condition inupdateAll() toOrderFood.order_num' => $order_num.

People are also looking for solutions to the problem: apache - PHP proc_open pipe anomaly (Win7/Apache2.2)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.