这是我的模特:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Hash;
class Domain extends BaseModel {
protected $fillable = ['user_id', 'name', 'username', 'password', 'plan', 'payment', 'status', 'duration'];
protected $hidden = ['password'];
protected $rules = [
'user_id' => [
'required',
'integer',
'exists:users,id'
],
'name' => [
'required',
'regex:/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z][a-z0-9-]{0,61}[a-z0-9])$/i',
'unique:domains,name',
],
'username' => [
'sometimes',
'nullable',
'min:1',
'max:16',
'unique:domains,username',
],
'password' => [
'sometimes',
'nullable',
'min:0',
'max:65',
],
'plan' => [
'sometimes',
'nullable',
],
'payment' => [
'required',
'string',
'max:40',
'in:webpos,cheque'
],
'status' => [
'sometimes',
'nullable',
'integer',
'in:0,1',
],
'duration' => [
'sometimes',
'nullable',
'integer',
'min:1',
'max:10',
]
];
protected $attributeNames = [
'user_id' => 'Domain Sahibi',
'name' => 'Domain Adı',
'payment' => 'Ödeme Şekli',
'status' => 'Domain Durumu',
'duration' => 'Domain Süresi'
];
public function setUsernameAttribute($value)
{
if ( is_null($value) ){
$value = str_random(16);
}
$this->attributes['username'] = strtolower($value);
}
public function setPasswordAttribute($value)
{
if ( is_null($value) ){
$value = str_random(16);
}
$this->attributes['password'] = Hash::make($value);
}
public function setPlanAttribute($value)
{
$this->attributes['plan'] = strtolower($value);
}
public function setNameAttribute($value){
$this->attributes['name'] = str_replace('www.', '', $value);
}
public function setStatusAttribute($value)
{
if ( is_null($value) ){
$value = 0;
}
$this->attributes['status'] = (int)$value;
}
public function setDurationAttribute($value)
{
if ( is_null($value) ){
$value = 1;
}
$this->attributes['duration'] = $value;
}
}
这是我的控制者:
$req = $request->only(['user_id', 'name', 'payment', 'status', 'duration']);
$result = $this->domain->add($req);
我有这个错误
&#34;无效请求SQLSTATE [HY000]:常规错误:1364字段&#39;用户名&#39;没有默认值(SQL:插入
domains
(user_id
,name
,payment
,status
,duration
,updated_at
,created_at
)值(1,deneme-1.com,check,0,1,2017-07-03 13:58:03,2017-07-03 13:58:03) )&#34;
为什么用户名和密码会转到sql?
我将这些添加到可填充数组中。我无法弄清楚为什么没有工作呢?
我不希望用户名和密码随附请求。我想设置默认的str_random。但不是wokring?
问题出在哪里?
是否为null come属性设置默认属性是正确的方法?
答案 0 :(得分:0)
我通过替换:
来修复它$req = $request->only(['user_id', 'name', 'payment', 'status', 'duration']);
使用:
$req = array_merge($request->only(['user_id', 'name', 'payment', 'status', 'duration']), ['username' => null, 'password' => null]);
答案 1 :(得分:0)
因为您将&#39;用户名&#39; 放在变量 $ fillable var中 并且您的数据库中的列必须是 nullable()。