首页 > 解决方案 > 使用 eloquent laravel 将默认值设置为一行

问题描述

我使用 laravel 和 post 和 get 方法创建了一个资源控制器:

class MyController extends Controller{
    //get method when page is visited
    public function index()
    {
        $data=array(
            'title'=>'Standard Stock',
            'standards'=>DB::table('standards')
            ->join('ps_product_lang','ps_product_lang.id_product','=','standards.id_product')
            ->select('standards.*','ps_product_lang.name')
            ->get()
        );
        return view('pages.standards')->with($data);
    }

    //post method to update value

     public function update(Request $request, $id)
   {

   $this->validate($request,[
        'quantity'=>'required'
    ]);
    $standard=Standard::find($id);
    $standard->quantity=$request->input('quantity');
    $standard->save();
    return redirect('/standards')->with('success','Quantity Updated');
    }
}

它现在工作正常,但问题是我的 ps_product_lang 数据库中有 2000 个产品,我想将$standard->quantity它们中的每一个都设置为 15。update()我曾经通过控制器中的功能更新数量值。

但是现在我想将初始值设置为 15,$standard->quantity并且我绝对不会单击 2000 时间表单按钮来提交发布请求。

我的问题是:有什么方便的方法可以将所有$standard->quantity值设置为 15?不接触其他代码?

标签: phplaravel

解决方案


有几种选择。

1) SQL 更新

您可以使用 SQL 查询更新数据库并将所有行设置为数量 = 15

UPDATE ps_product_lang SET quantity = 15

2) Laravel 工作

您可以为此创建一个工作。

请参阅此处的文档:https ://laravel.com/docs/5.6/queues#creating-jobs

3) 迁移

您可以为此使用迁移并为此列设置默认值。

Schema::table('ps_product_lang ', function (Blueprint $table) {
            $table->string('quantity')->default('15')->change();
        });

请参阅文档上的迁移详细信息:https ://laravel.com/docs/5.6/migrations#modifying-columns


推荐阅读