![](/img/trans.png)
[英]Laravel not adhering to Mass Assignment $fillable rules for related model update
[英]Laravel not adhering to the set tablename in the Model specifically when using the ->create() function
我正在使用 Laravel 8 创建 API 并遇到了一个相当麻烦的问题。
调用创建命令Laravel找不到正确的表,输出错误。
Illuminate\Database\QueryException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'homestead.user' doesn't exist (SQL: select count(*) as aggregate from `user` where `email` = test@gmail.com) in file /home/vagrant/code/feniks/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 678
错误 output 是正确的,因为表名实际上是 homestead.users。 我已经看到一些关于 Laravel 在自动查找时自动在表格末尾添加“s”的问题,但由于这似乎是相反的,我找不到任何解决方案。 奇怪的部分是所有其他命令; 更新、显示、索引和销毁确实找到了正确的表。 其他一些问题的答案给出了在 model 中手动设置表名的解决方案,如下所示:
protected $table = 'users';
然而,这似乎并没有改变任何东西。
这是我使用的用户 Model:
class User extends Authenticatable
{
use Notifiable, HasApiTokens, SoftDeletes, HasFactory;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* @return HasMany
*/
public function memberships() : hasMany
{
return $this->hasMany(Membership::class, 'user_id');
}
}
以及处理 API 调用的 controller 方法:
public function store(): Response
{
if (!$object = $this->model->create($this->inputStore()))
{
return ResponseBuilder::error(409);
}
return ResponseBuilder::success($object, 201);
}
这是一个可以与之比较的有效 destroy() 方法:
public function destroy(): Response
{
foreach (request()->except('membership') as $item)
{
if($object = $this->model->find($item))
{
$object->delete();
$this->success[] = $object;
}
else
{
$this->failed[] = $item;
}
}
if($this->failed)
{
return ResponseBuilder::error( 404,[],['failed' => $this->failed,'success' => $this->success]);
}
return ResponseBuilder::success($this->success, 200);
}
inputStore() 方法只是验证数据的一种奇特方式,但如果它被证明是有用的,这里是:
protected function inputStore($attributes = []): array
{
if (!empty($attributes))
{
foreach ($attributes as $attribute => $value)
{
request()->merge([
$attribute => $value
])->except('membership');
}
}
return request()->validate([
'email' => 'required|email|unique:user',
'password' => 'required|max:255',
'first_name' => 'string|max:255',
'last_name' => 'string|max:255',
'dob' => 'date',
'phone' => 'string|max:255',
'language' => 'string|max:8',
]);
}
原来在 validate() function 中发生了一个错误,其中“unique:user”参数应该是“unique:users”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.