BannerAdmin.php 1.71 KB
<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use think\facade\Db;

class BannerAdmin extends BaseController
{
    public function list()
    {
        $rows = Db::name('banner')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();

        return json(['code' => 0, 'msg' => 'ok', 'data' => ['list' => $rows]]);
    }

    public function save()
    {
        $id        = (int) $this->request->post('id', 0);
        $imageUrl  = trim((string) $this->request->post('image_url', ''));
        $title     = trim((string) $this->request->post('title', ''));
        $subtitle  = trim((string) $this->request->post('subtitle', ''));
        $sort      = (int) $this->request->post('sort', 0);
        $status    = (int) $this->request->post('status', 1);

        if ($imageUrl === '') {
            return json(['code' => 400, 'msg' => '图片地址必填', 'data' => []]);
        }

        $now = date('Y-m-d H:i:s');
        $row = [
            'image_url'   => $imageUrl,
            'title'       => $title,
            'subtitle'    => $subtitle,
            'sort'        => $sort,
            'status'      => $status === 0 ? 0 : 1,
            'update_time' => $now,
        ];

        if ($id <= 0) {
            $row['create_time'] = $now;
            Db::name('banner')->insert($row);
        } else {
            Db::name('banner')->where('id', $id)->update($row);
        }

        return json(['code' => 0, 'msg' => '已保存', 'data' => []]);
    }

    public function delete(int $id)
    {
        Db::name('banner')->where('id', $id)->delete();
        return json(['code' => 0, 'msg' => '已删除', 'data' => []]);
    }
}