You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.9 KiB
80 lines
1.9 KiB
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\AgentProduct;
|
|
use App\Models\UserFav;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
/**
|
|
* 用户收藏
|
|
* Class UserFavController
|
|
* @package App\Http\Controllers\Api
|
|
*/
|
|
class UserFavController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$list = UserFav::query()
|
|
->with([
|
|
'agentProduct:id,price,original_price,title,pictures',
|
|
])
|
|
->where('user_id', $this->user_id)
|
|
->select('id', 'agent_product_id', 'product_id', 'created_at')
|
|
->orderBy('id', 'DESC')
|
|
->simplePaginate(15);
|
|
if (!$list->isEmpty()) {
|
|
$list = $list->toArray();
|
|
$prefix = Storage::disk('public')->url('');
|
|
if ($list['data']) {
|
|
foreach ($list['data'] as &$v) {
|
|
if (!empty($v['agent_product']['pictures'])) {
|
|
//多图
|
|
$v['agent_product']['pictures'] = array_map(function ($v) use ($prefix) {
|
|
return strpos($v, $prefix) === false ? $prefix . $v : $v;
|
|
}, $v['agent_product']['pictures']);
|
|
|
|
//单图
|
|
$v['agent_product']['picture'] = $prefix . $v['agent_product']['picture'];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return $this->success($list);
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
$id = (int)request()->input('agent_product_id');
|
|
|
|
$agent_product = AgentProduct::find($id);
|
|
if (!$agent_product) {
|
|
return $this->error('产品不存在或已被删除');
|
|
}
|
|
|
|
//如果不存在则创建
|
|
UserFav::query()->firstOrCreate([
|
|
'user_id' => $this->user_id,
|
|
'agent_product_id' => $agent_product->id,
|
|
'product_id' => $agent_product->product_id,
|
|
]);
|
|
|
|
return $this->success();
|
|
}
|
|
|
|
public function delete()
|
|
{
|
|
$id = (int)request()->input('agent_product_id');
|
|
|
|
$fav = UserFav::query()->where([
|
|
'user_id' => $this->user_id,
|
|
'agent_product_id' => $id,
|
|
])->first();
|
|
if (!$fav) {
|
|
return $this->error('收藏不存在');
|
|
}
|
|
$fav->delete();
|
|
return $this->success();
|
|
}
|
|
}
|