From df69c2aea42478b43f82f26950cb573b8388982a Mon Sep 17 00:00:00 2001 From: wolfcode <37436228+wolf-leo@users.noreply.github.com> Date: Mon, 1 Jul 2024 13:51:58 +0800 Subject: [PATCH] refactor(admin-model): change MallGoods cate relation from BelongsTo to HasOne The relationship between MallGoods and MallCate has been updated to reflect a HasOne association rather than a BelongsTo. This change is reflected in the cate() method of the MallGoods model, enhancing the flexibility of the model relationships. --- app/admin/controller/mall/Goods.php | 18 +++--------------- app/admin/model/MallGoods.php | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/app/admin/controller/mall/Goods.php b/app/admin/controller/mall/Goods.php index 14beecd..444beb8 100644 --- a/app/admin/controller/mall/Goods.php +++ b/app/admin/controller/mall/Goods.php @@ -20,8 +20,6 @@ use think\response\Json; class Goods extends AdminController { - protected bool $relationSearch = true; - public function __construct(App $app) { parent::__construct($app); @@ -36,20 +34,10 @@ class Goods extends AdminController public function index(Request $request): Json|string { if ($request->isAjax()) { - if (input('selectFields')) { - return $this->selectList(); - } + if (input('selectFields')) return $this->selectList(); list($page, $limit, $where) = $this->buildTableParams(); - $count = $this->model - ->withJoin('cate', 'LEFT') - ->where($where) - ->count(); - $list = $this->model - ->withJoin('cate', 'LEFT') - ->where($where) - ->page($page, $limit) - ->order($this->sort) - ->select()->toArray(); + $count = $this->model->where($where)->count(); + $list = $this->model->with(['cate'])->where($where)->page($page, $limit)->order($this->sort)->select()->toArray(); $data = [ 'code' => 0, 'msg' => '', diff --git a/app/admin/model/MallGoods.php b/app/admin/model/MallGoods.php index 68f717d..0fb039d 100644 --- a/app/admin/model/MallGoods.php +++ b/app/admin/model/MallGoods.php @@ -2,8 +2,9 @@ namespace app\admin\model; - use app\common\model\TimeModel; +use think\model\relation\BelongsTo; +use think\model\relation\HasOne; class MallGoods extends TimeModel { @@ -12,9 +13,18 @@ class MallGoods extends TimeModel protected $deleteTime = 'delete_time'; - public function cate() + // * +++++++++++++++++++++++++++ + // | 以下两种写法适用于 with 关联 + // * +++++++++++++++++++++++++ + + // public function cate(): BelongsTo + // { + // return $this->belongsTo('app\admin\model\MallCate', 'cate_id', 'id'); + // } + + public function cate(): HasOne { - return $this->belongsTo('app\admin\model\MallCate', 'cate_id', 'id'); + return $this->hasOne(MallCate::class, 'id', 'cate_id'); } } \ No newline at end of file