我正在使用 Controller 中的验证更新我的用户表。我已经为同一 Controller 中的两个表创建了相同的验证。
当我使用此代码时:
User::where('id',$data->user_id)->update($this->validateField($data->user_id));
它显示
Error: Column not found: 1054 Unknown column 'address_name'
这是正确的,因为用户表没有列“address_name”,但它可以使用此代码,没有任何错误
$user = User::where("id",$data->user_id)->firstOrFail();
$user->update($this->validateField($data->user_id));
这两个代码之间有什么不同,为什么它不起作用(显示未知列错误)以及为什么它在没有列错误的情况下起作用?
这是我的 validateField 方法
public function validateField($id)
{
return request()->validate([
'address_name' => 'required|string|max:255',
'mobile' => 'required|numeric|digits_between:10,13',
'land_line' => 'required|numeric|digits_between:10,13',
'min_order' => 'required',
'payment_method' => 'required',
'open_time' => 'required',
'close_time' => 'required',
'address'=>'required|string|max:255',
'city'=>'required|string|max:255',
'country'=>'required|string|max:255',
'is_active' => 'required',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|email|max:255|unique:users,email,'.$id.',id,deleted,0',
'password' => 'sometimes|required|min:8',
]);
}
我的用户表
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('password');
$table->string('mobile');
$table->tinyInteger('user_role')->unsigned();
$table->tinyInteger('is_active')->unsigned()->default(1);
$table->datetime('last_login')->nullable();
$table->tinyInteger('deleted')->unsigned()->default(0);
$table->dateTime('created_at')->nullable();
$table->dateTime('updated_at')->nullable();
$table->integer('updated_by')->nullable();
$table->rememberToken();
});
最佳答案
嗯
User::where('id',$data->user_id)->update($this->validateField($data->user_id));
这将更新与 where
对应的所有记录,并将字段作为参数传递给 update
函数,这只是 where
将只有一个匹配项(因为您将 where 子句应用于主键),如果有多个匹配项,则所有记录都将被更新。
请记住,where
函数将返回一个 Builder
,因此 update
函数是class Builder
:这意味着只有一个查询(update ... set ... where id =/*your id*/
)。
这个代替
User::where("id",$data->user_id)->firstOrFail()->update($this->validateField($data->user_id))
将首先获取与 where
子句匹配的第一条记录,因此会有一个类似 select .. from .. where id=/*your id*/
的查询>,然后 Model
将被调用 update
函数,因此这里调用的函数 id 为 Model -> update
函数,之前是Builder -> update
,因此将有第二个更新查询。
不同的行为是由两个类中 update
函数的不同实现引起的。实际上,在我的服务器上,如果传递给 update
的数组内的某些字段不是表字段,这两种方法都会抛出错误,不知道为什么第一个方法工作正常
关于php - 未找到列 : Unknown column using Model reference but work with object reference laravel 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023246/