The function that deletes unnecessary items, orders and users lifetime which has already gone
{
$stateProcess = Order::PROCESS;
$stateOrdered = Order::ORDERED;
$max_lifetime = Yii::app()->getModule('shoppingcart')->max_lifetime;
$connection = Yii::app()->db;
Yii::beginProfile('garbageCollector');
$ordersToRemove = $command=$connection
->createCommand(
"SELECT ProcessOrder.id AS order_id,
ProcessOrder.user_id,
IF((DATE_ADD(IFNULL(MAX(Item.ordered_at),ProcessOrder.started_at), INTERVAL :max_lifetime MINUTE) < NOW()) , TRUE , FALSE) AS order_to_remove,
IF((COUNT(OrderedOrder.id) < 1) , TRUE, FALSE) AS user_to_remove
FROM {{order}} AS ProcessOrder
LEFT JOIN {{item}} AS Item
ON ProcessOrder.id = Item.order_id
LEFT JOIN {{order}} AS OrderedOrder
ON ProcessOrder.user_id = OrderedOrder.user_id AND OrderedOrder.ordered = :ordered
WHERE ProcessOrder.ordered=:process GROUP BY ProcessOrder.id
HAVING order_to_remove = TRUE")
->bindParam(":max_lifetime",$max_lifetime,PDO::PARAM_STR)
->bindParam(":ordered",$stateOrdered,PDO::PARAM_STR)
->bindParam(":process",$stateProcess,PDO::PARAM_STR)
->queryAll();
foreach($ordersToRemove as $order){
$user_to_remove = $order['user_to_remove'];
$transaction = $connection->beginTransaction();
try
{
$connection->createCommand(
"DELETE FROM {{item}} WHERE {{item}}.order_id = :order_id"
)
->bindParam(":order_id",$order['order_id'],PDO::PARAM_STR)
->execute();
if($user_to_remove){
$connection->createCommand(
"DELETE FROM {{tmp_user}} WHERE {{tmp_user}}.id = :user_id"
)
->bindParam(":user_id",$order['user_id'],PDO::PARAM_STR)
->execute();
}
$connection->createCommand(
"DELETE FROM {{order}} WHERE {{order}}.id = :order_id"
)
->bindParam(":order_id",$order['order_id'],PDO::PARAM_STR)
->execute();
$transaction->commit();
}
catch(Exception $e){
$transaction->rollback();
}
}
Yii::endProfile('garbageCollector');
}