我正在尝试为 laravel 迁移设置默认值。我正在使用 SQLite。
当我尝试使用分配了默认值的字段插入记录时,返回错误:SQL 错误或缺少数据库(表客户没有名为 country 的列)
这是迁移脚本:
php
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('contact_person_first_name');
$table->string('contact_person_name');
$table->string('contact_person_email_address');
$table->string('address');
$table->string('zipCode');
$table->string('city');
$table->string('country')->default("BELGIË");
$table->string('vat_number')->default("BE");
$table->timestamps();
Controller : * Store a newly created resource in storage.
*
* @param CreateCustomerRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(CreateCustomerRequest $request)
{
Customer::create($request->validated());
return response()->redirectTo('/customers');
}
请求: /**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|min:2|max:255',
'contact_person_first_name' => 'required|string|min:2|max:255',
'contact_person_name' => 'required|string|min:2|max:255',
'contact_person_email_address' => 'required|email',
'address' => 'required|string|min:2|max:255',
'zipCode' => 'required|string|min:4|max:10',
'city' => 'required|string|min:2|max:255',
'country' => 'nullable|string|min:2|max:255',
'vat_number' => 'nullable|min:12|max:12'
];
}
我要执行的sql脚本:来自数据库 GUI 的一些屏幕截图
最佳答案
您已在数据库层中设置了默认值。但它不可为空。这导致了这里的问题。您的请求国家/地区为空,并且您在创建新行时分配了该空值。要么你必须使用 nullable 来插入空值,要么你必须在创建时设置一个值。
用于数据库
$table->string('country')->nullable()->default("BELGIË");
对于您的情况,这不是一个好的解决方案。所以你可以使用一些东西Customer::create([
'name' => $request->name,
'country' => $request->country ?? 'BELGIË',
//other attributes
]);
关于如果请求值为空,Laravel 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64134554/