laravel-admin 互动批量操作

一、首先根据文档生成批量操作类

先运行下面的命令生成批量操作类:

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();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值