78 lines
2.2 KiB
PHP
78 lines
2.2 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Controllers;
|
||
|
||
use App\Http\Requestes\CropRequest;
|
||
use App\Http\Resources\CropResource;
|
||
use App\Models\Crop;
|
||
use App\Models\CropYield;
|
||
use Illuminate\Http\Request;
|
||
|
||
class CropController extends Controller
|
||
{
|
||
public function index(Request $request)
|
||
{
|
||
$query = Crop::filter($request->input());
|
||
$list = $query->sort()->get();
|
||
|
||
return $this->json(CropResource::collection($list));
|
||
}
|
||
|
||
public function store(CropRequest $request)
|
||
{
|
||
$input = $request->input();
|
||
//如果有上级,录入path
|
||
if ($input['parent_id'] ?? 0) {
|
||
$parent = Crop::findOrFail($input['parent_id']);
|
||
$input['path'] = ($parent?->path ?? '').$parent?->id.'-';
|
||
}
|
||
Crop::create($input);
|
||
|
||
return $this->success('添加成功');
|
||
}
|
||
|
||
public function show(Crop $crop)
|
||
{
|
||
return $this->json(CropResource::make($crop));
|
||
}
|
||
|
||
public function update(Crop $crop, CropRequest $request)
|
||
{
|
||
//如果原本是结点,不允许修改为非节点
|
||
//如果原本非结点,且有子节点,同样无法修改;
|
||
|
||
$input = $request->input();
|
||
if ($input['is_end'] != $crop->is_end) {
|
||
if ($crop->is_end || Crop::where(['parent_id', $crop->id])->exists()) {
|
||
return $this->error('无法修改结点状态');
|
||
}
|
||
}
|
||
|
||
//如果有上级,录入path
|
||
if ($input['parent_id'] ?? 0) {
|
||
$parent = Crop::findOrFail($input['parent_id']);
|
||
$input['path'] = ($parent?->path ?? '').$parent?->id.'-';
|
||
}
|
||
|
||
$crop->update(array_merge($request->input()));
|
||
|
||
return $this->success('修改成功');
|
||
}
|
||
|
||
public function destroy(Crop $crop)
|
||
{
|
||
//如果有关联数据,无法删除
|
||
if (CropYield::where('crop_id', $crop->id)->exists()) {
|
||
return $this->error('该结点有关联产量数据, 无法删除');
|
||
}
|
||
//如果有子节点,无法删除
|
||
if (Crop::where(['parent_id', $crop->id])->exists()) {
|
||
return $this->error('该结点有关联产量数据, 无法删除');
|
||
}
|
||
|
||
$crop->delete();
|
||
|
||
return $this->success('删除成功');
|
||
}
|
||
}
|