当我尝试model->create($input)
或model->update($input)
输入通过命令总线传递时(而不是在我的控制器中执行),Laravel不会忽略以下划线开头的值,如预期的那样。
Illuminate \ Database \ QueryException
SQLSTATE [HY000]:常规错误: 1没有这样的列:_token(SQL:update" guest" set" _token" = ...
我做错了什么?
# GuestRegistrationCommandHandler.php
public function handle($command)
{
if ($this->guest->exists($command->input['email']))
{
$guest = $this->guest->registerExisting($command->input);
}
else
{
$guest = $this->guest->registerNew($command->input);
}
$this->dispatcher->dispatch($guest->releaseEvents());
return Redirect::to('/register/thankyou');
}
# EloquentGuestRepository.php
public function registerExisting(array $input)
{
$guest = $this->guest->update($input);
$this->raise(new GuestWasRegistered($guest));
return $guest;
}
我已经更改了一些代码,现在在我的控制器中,我现在只是用下划线排除输入名称。
# RegistrationController.php
public function store()
{
try
{
$this->registration->validate(Input::all());
$command = new GuestRegistrationCommand(Input::except('_token', '_tos'));
$this->commandBus->execute($command);
}
catch(FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e);
}
}
但是,现在我收到了错误:
Illuminate \ Database \ QueryException
SQLSTATE [23000]:诚信 约束违规:19列电子邮件不是唯一的(SQL:更新 "客人" ...
电子邮件不是唯一的,因为电子邮件与我正在更新的电子邮件相同。在我尝试使用CommandBus之前,这从未给我带来任何问题。
答案 0 :(得分:1)
使用Mass Assignment时,您必须在模型中声明$fillable
属性,以允许您要填写的字段或使用$guarded
属性,例如:
// Only these fields will be inserted even there are more
protected $fillable = array('first_name', 'last_name', 'email');
您也可以在Model
:
// These fields will not be inserted even
// they are provided in an array with other
protected $guarded = array('id', 'password');
因此,您使用create(Input::all())
创建的模型只需添加$fillable
或$guarded
属性。
答案 1 :(得分:0)
问题是我实际上并没有更新现有的模型,所以当在新模型上调用update()
时,Eloquent会变得很奇怪。
重构一下修复了一切。
# RegistrationController.php
public function store()
{
$input = Input::all();
try
{
$this->registration->validate($input);
$command = new GuestRegistrationCommand($input);
$this->commandBus->execute($command);
return Redirect::to('/register/thankyou');
}
catch(FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e);
}
}
-
# GuestRegistrationCommandHandler.php
public function handle($command)
{
$guest = $this->guest->register($command->input);
$this->dispatcher->dispatch($guest->releaseEvents());
}
解决问题的关键是首先找到现有客人的基本步骤,如下所示:
# EloquentGuestRepository.php
public function register(array $input)
{
$guest = $this->find($input['email']);
if (is_null($guest))
{
$guest = $this->guest->create($input);
}
else
{
$guest->update($input);
}
$this->raise(new GuestWasRegistered($this));
return $this;
}