<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Db;
class Favorite extends Api{
protected $noNeedRight = ['*'];
public function index(){
$userId = $this->auth->id;
$type = input('post.type', 1, 'int');
$page = input('post.page', 1, 'int');
$model = new \app\common\model\Favorite();
$where['f.user_id'] = $userId;
$where['f.type'] = $type;
$where['f.status'] = $model::STATUS_Y;
if($type == $model::TYPE_GOODS) {
$rows = Db::name('favorite')->alias('f')
->join('goods g', 'f.relation_id = g.id', 'left')
->where($where)
->field('from_unixtime(f.create_time) as time, f.type, g.goods_name as name, g.original_image as img, g.id')
->order(['f.create_time' => 'desc'])
->page($page, 20)
->select();
} else {
$rows = Db::name('favorite')->alias('f')
->join('business b', 'f.relation_id = b.id', 'left')
->where($where)
->field('from_unixtime(f.create_time) as time, b.name, b.logo as img, b.id')
->order(['f.create_time' => 'desc'])
->page($page, 20)
->select();
}
$this->success('查询成功', $rows);
}
public function add(){
$userId = $this->auth->id;
$id = input('post.id');
$type = input('post.type');
if(!$id || !$type) {
$this->error('参数错误');
}
$model = new \app\common\model\Favorite();
$types = $model::$_type;
if(!in_array($type, array_keys($types))){
$this->error('类型错误');
}
if($type == $model::TYPE_GOODS) {
$data = Db::name('goods')->find($id);
!$data && $this->error('商品不存在');
} else {
$data = Db::name('business')->find($id);
!$data && $this->error('店铺不存在');
}
$row = $model
->where(['user_id' => $userId, 'type' => $type, 'relation_id' => $id, 'status' => $model::STATUS_Y])
->find();
if($row) {
$this->success('已收藏');
}
$res = $model->addRecord($userId, $type, $id);
if($res) {
$this->success('收藏成功');
} else {
$this->error('收藏出错');
}
}
public function cancel(){
$userId = $this->auth->id;
$id = input('post.id');
$type = input('post.type');
if(!$id || !$type) {
$this->error('参数错误');
}
$model = new \app\common\model\Favorite();
$types = $model::$_type;
if(!in_array($type, array_keys($types))){
$this->error('类型错误');
}
$ids = explode(',', $id);
$res = $model
->save(
['status' => $model::STATUS_C],
['user_id' => $userId, 'type' => $type, 'status' => $model::STATUS_Y, 'relation_id' => ['in',$ids]]);
if($res !== false) {
$this->success('取消成功');
} else {
$this->error('取消出错');
}
}
}