一、首先根据文档生成批量操作类
先运行下面的命令生成批量操作类:
php artisan admin:action Post\\BatchReplicate --grid-batch --name="批量复制"
二、在控制器中添加如下代码
$grid->batchActions(function ($batch) {
$batch->add(new BatchReplicate());
});
三、在批量操作类里
<?php
namespace App\Admin\Actions\Post;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
class TextBatchEditor extends BatchAction
{
public $name = '翻译批量编辑';
//注意这里边的参数,应该也可以使用Model $model, Request $request,可以自己打印一下看看
public function handle( Collection $collection, Request $request)
{
$fanYi = $request->get('fanyi_platform');
$fanYiDoc = $request->get('fanyidoc_platform');
$fanYiImg = $request->get('fanyiimg_platform');
$trans = $request->get('trans_plat');
//因为是批量操作,会有多条数据,注意循环处理
foreach($collection as $model) {
$model->update([
'fanyi_platform' => $fanYi ? $fanYi : $model->fanyi_platform,
'fanyidoc_platform' => $fanYiDoc ? $fanYiDoc : $model->fanyidoc_platform,
'fanyiimg_platform' => $fanYiImg ? $fanYiImg : $model->fanyiimg_platform,
'trans_plat' => $trans ? $trans : $model->trans_plat
]);
}
//会自动刷新页面
return $this->response()->success('批量修改成功')->refresh();
}
//form方法相当于生成了一个表单,点击按钮会自动跳出
public function form()
{
$this->select('fanyi_platform', "文本翻译")->options(config("platform"));
$this->select('fanyidoc_platform', "文档翻译")->options(config("fanyi_platform.doc"));
$this->select('fanyiimg_platform', "图片翻译")->options(config("fanyi_platform.img"));
$this->select('trans_plat', "语音转写")->options(config("fanyi_platform.trans"));
}
}
四、进阶提升-大佬完善的代码
(用到了php反射机制 php reflection)
public function handle( Collection $collection, Request $request)
{
$options = $request->only(['fanyi_platform', 'fanyidoc_platform', 'fanyiimg_platform', 'trans_plat']);
// 过滤为空的
$options = array_filter($options);
$ids = $collection->pluck('id')->toArray();
$model = $collection->first();
if ($options) {
//通过模型找到类,用类修改数据库数据
get_class($model)::query()->whereIn('id', $ids)->update($options);
}
return $this->response()->success('批量修改成功')->refresh();
}