![](/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.