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
Answer
Solution:
You are trying to update your
OrderFood
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 the
order_num
for yourcheck_num
. Then change the condition inupdateAll()
toOrderFood.order_num' => $order_num
.