Files
xk-api-old-laravel/app/Http/Controllers/Member/DrugController.php
2025-01-11 14:16:20 +08:00

111 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers\Member;
use App\Models\DrugCategory;
use App\Models\DrugStoreRelation;
use App\Models\YiiModels\Drug;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* 药品
*/
class DrugController extends MemberBaseController
{
/**
* 药品分类
*
* @return void
*/
public function drugCategory()
{
json_success(DrugCategory::getCategory());
}
/**
* 商品列表(带库存)
*
* @return void
*/
public function drugLists()
{
$category_first = request('category_first');
$category_second = request('category_second');
$keyword = request('keyword');
// $this->toValidator([
// 'category_first' => 'required|integer',
// 'category_second' => 'required|integer',
// ], [], [
// 'category_first' => '一级分类',
// 'category_second' => '二级分类',
// ]);
$drugs = Drug::with([
'drugstoreDrug' => function (Relation $relation) {
$relation->select(['drug_id', 'price', 'stock'])
->where('drugstore_id', $this->getDrugstoreId());
},
])
->select([
'id', 'drug_name', 'source', 'type', 'is_otc', 'category_first', 'category_second',
'usage', 'small_info', 'specification', 'image',
])
->whereHasIn('drugStoreRelation', function (Builder $builder) {
$builder->where('status', DrugStoreRelation::STATUS_ON)
->where('store_id', $this->getStoreId());
})
->when($keyword, function (Builder $builder) use ($keyword) {
$builder->where('drug_name', 'like', "%$keyword%");
})
->where('status', Drug::STATUS_ON)
->where('type_id', [Drug::TYPE_CHINESE_DRUG, Drug::TYPE_PELLET_PATENT])
->where('is_otc', Drug::IS_OTC_FALSE)
->where('category_first', $category_first)
->where('category_second', $category_second)
->get();
json_success($drugs);
}
/**
* 商品详情
*
* @return void
*/
public function drugDetail()
{
$id = $this->getId();
/* @var Drug $drug */
$drug = Drug::with([
'drugStoreRelation' => function (Relation $relation) {
$relation->select(['store_id', 'drug_id', 'total_sales_volume', 'status'])
->with(['store:id,name'])
->where('store_id', $this->getStoreId());
},
'drugstoreDrug' => function (Relation $relation) {
$relation->select(['drugstore_id', 'drug_id', 'price', 'stock'])
->where('drugstore_id', $this->getDrugstoreId());
},
])
->select([
'id', 'drug_name', 'source', 'type', 'is_otc', 'category_first', 'category_second',
'usage', 'specification', 'image', 'small_info', 'info', 'content', 'status',
])
->whereHasIn('drugStoreRelation', function (Builder $builder) {
$builder->where('store_id', $this->getStoreId());
})
->where('id', $id)
->first();
if (!$drug || !$drug->drugStoreRelation || !$drug->drugstoreDrug) {
json_error('商品不存在');
}
if ($drug->status != Drug::STATUS_ON || $drug->drugStoreRelation->status != Drug::STATUS_ON) {
json_error('商品已下架');
}
json_success($drug);
}
}