82 lines
2.5 KiB
PHP
82 lines
2.5 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace app\api\logic;
|
||
|
|
||
|
use app\common\logic\BaseLogic;
|
||
|
use app\common\model\Cart;
|
||
|
use app\common\model\CartProduct;
|
||
|
use app\common\model\Dishes;
|
||
|
use app\common\model\DishesProduct;
|
||
|
use think\facade\Db;
|
||
|
|
||
|
class CartLogic extends BaseLogic
|
||
|
{
|
||
|
|
||
|
public function list($params)
|
||
|
{
|
||
|
$query = Cart::with(['cartDishes', 'cartProduct' => function ($query) {
|
||
|
$query->with(['product', 'unit']);
|
||
|
}])->where('uid', $params['uid'])->where('paid', 0)->where('buy_now', 0);
|
||
|
if (!empty($params['keyword'])) {
|
||
|
$dishesIds = Dishes::whereLike('name', "%{$params['keyword']}%")->column('id');
|
||
|
$query->whereIn('dishes_id', $dishesIds);
|
||
|
}
|
||
|
$data = $query->page($params['page'], $params['limit'])->select()->toArray();
|
||
|
return $data;
|
||
|
}
|
||
|
|
||
|
public function count($params)
|
||
|
{
|
||
|
return Cart::where('uid', $params['uid'])->where('paid', 0)->where('buy_now', 0)->count();
|
||
|
}
|
||
|
|
||
|
public function delete($params)
|
||
|
{
|
||
|
Db::startTrans();
|
||
|
try {
|
||
|
CartProduct::destroy(['cart_id' => $params['id']]);
|
||
|
Cart::destroy(['id' => $params['id'], 'uid' => $params['uid']]);
|
||
|
Db::commit();
|
||
|
return true;
|
||
|
} catch (\Exception $e) {
|
||
|
Db::rollback();
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public function add($params)
|
||
|
{
|
||
|
Db::startTrans();
|
||
|
try {
|
||
|
$cart = new Cart();
|
||
|
if (!$cart->save($params)) {
|
||
|
throw new \Exception('添加购物车失败');
|
||
|
}
|
||
|
$products = DishesProduct::where('dishes_id', $params['dishes_id'])->select()->toArray();
|
||
|
$cartProductData = [];
|
||
|
$datetime = date('Y-m-d H:i:s');
|
||
|
foreach ($products as $product) {
|
||
|
$cartProductData[] = [
|
||
|
'uid' => $params['uid'],
|
||
|
'dishes_id' => $params['dishes_id'],
|
||
|
'product_id' => $product['product_id'],
|
||
|
'cart_id' => $cart->id,
|
||
|
'nums' => $product['nums'],
|
||
|
'unit_id' => $product['unit_id'],
|
||
|
'create_time' => $datetime,
|
||
|
'update_time' => $datetime,
|
||
|
];
|
||
|
}
|
||
|
if (!CartProduct::insertAll($cartProductData)) {
|
||
|
throw new \Exception('添加购物车商品失败');
|
||
|
}
|
||
|
Db::commit();
|
||
|
return true;
|
||
|
} catch (\Exception $e) {
|
||
|
Db::rollback();
|
||
|
throw $e;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|