php - 使用 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?不接触其他代码?
解决方案
有几种选择。
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
推荐阅读
- java - What is spring data jpa and which orm framework does it use?
- java - 如何以编程方式将系统 UI 设置为暗模式(不是应用程序)?
- android - 如何更改 material.io 中文本字段的轮廓?
- mongodb - 将现有的 maprdb 迁移到 mongodb。应用中使用的springboot hadoop和maprdb
- django - django_graphene 在错误的地方寻找包“六”?
- bash - Bash 脚本不接受 -e 作为参数
- vue.js - WebStorm 无法解析 scss 导入
- c# - 如何仅从文件路径中获取文件
- c# - 将 XML 值放入组合框
- python - 启动 pytest 测试运行程序时,如何指定设置 pytest 固定装置的配置?