积分商品兑换

<?php

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\Order;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function createOrder()
    {
        $user = $this->request->user();
        $order_sn = get_order_sn('P');
        $goods_id = $this->request->input('goods_id', 1);
        $test = Goods::where('id', $goods_id)->first();
        $goods_integral = $test->integral * $goods_number;
        $order_status = 1;
        $sign_name = '兑换' . mb_substr($test->name, 0, 8, 'utf-8');
        $order = [
            'order_sn' => $order_sn,
            'store_id' => $store_id,
            'goods_id' => $goods_id,
            'goods_number' => $goods_number,
            'goods_integral' => $goods_integral,
            'user_id' => $user->id,
            'order_status' => $order_status,
        ];
        try {
            DB::beginTransaction();
            if ($user->point < $goods_integral) {
                return api_throw('当前账户积分余额不足!');
            }
            User::where('id', $user->id)->update(['point' => $user->point - $goods_integral]);
            $newUser = User::where('id', $user->id)->first();
            UsersSign::create([
                'user_id' => $user->id,
                'sign_name' => $sign_name,
                'sign_num' => '-' . $goods_integral,
                'sign_date' => 0,
                'before_change' => $user->point,
                'before_after' => $newUser->point,
            ]);
            Order::create($order);
            $goods = Goods::where('id', $goods_id)->first();
            if ($goods->stock == 0){
                return api_throw('该商品库存不足');
            }
            Goods::where('id', $goods_id)->decrement('stock', 1);
            DB::commit();
            return api_return();
        } catch (\Exception $exception) {
            DB::rollBack();
            return api_throw('兑换失败,' . $exception->getMessage());
    } }
    }
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 4

建议你修改下格式

2年前 评论
orange1994

自己看了不头疼吗

2年前 评论

给你提交了改进,简单的修改了下。

2年前 评论
开普勒 (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
1
粉丝
1
喜欢
0
收藏
3
排名:2549
访问:413
私信
所有博文
社区赞助商