belongsTo('FFProducts', 'product_id', 'id'); } /** * 查询用户是否收藏了指定商品 * @param int $userId 用户ID * @param int $productId 商品ID * @return bool|array false表示未收藏,array表示收藏信息 */ public static function isFavorite($userId, $productId) { $where = [ 'user_id' => $userId, 'product_id' => $productId, ]; $favorite = self::where($where)->find(); return $favorite ? $favorite->toArray() : false; } /** * 添加收藏 * @param int $userId 用户ID * @param int $productId 商品ID * @return bool|array 收藏结果 * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public static function addFavorite($userId, $productId) { // 检查是否已收藏 $favorite = self::where([ 'user_id' => $userId, 'product_id' => $productId, ])->find(); if ($favorite) { // 已收藏,返回已存在 return $favorite->toArray(); } // 新增收藏 $model = new self(); $model->user_id = $userId; $model->product_id = $productId; $model->save(); return $model->toArray(); } /** * 取消收藏 * @param int $userId 用户ID * @param int $productId 商品ID * @return bool 取消结果 */ public static function cancelFavorite($userId, $productId) { return self::where([ 'user_id' => $userId, 'product_id' => $productId, ])->delete(); } /** * 获取用户收藏列表 * @param int $userId 用户ID * @param int $page 页码 * @param int $limit 每页条数 * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public static function getUserFavoriteList($userId, $page = 1, $limit = 10) { $list = self::where('user_id', $userId) ->with(['product']) ->page($page, $limit) ->order('create_time', 'desc') ->select(); return $list ? $list->toArray() : []; } /** * 获取商品收藏数量 * @param int $productId 商品ID * @return int 收藏数量 */ public static function getProductFavoriteCount($productId) { return self::where('product_id', $productId)->count(); } /** * 批量取消收藏 * @param int $userId 用户ID * @param array $productIds 商品ID数组 * @return int 影响行数 */ public static function batchCancelFavorite($userId, $productIds) { return self::where('user_id', $userId) ->whereIn('product_id', $productIds) ->delete(); } /** * 关联用户表 * @return \think\model\relation\HasOne */ public function user() { return $this->hasOne(User::class, 'id', 'user_id'); } }