为什么雄辩的模型创建或更新不再像预期的那样工作


Why would eloquent model Create or Update no longer work as expected?

当我尝试通过命令总线输入model->create($input)model->update($input)时(而不是在我的控制器中这样做),Laravel不会忽略以下划线开头的值,如预期的那样。

照亮'数据库' QueryException

SQLSTATE[HY000]:错误:SQL: update "guests" 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);
    }
}

但是,现在我得到错误:

照亮'数据库' QueryException

SQLSTATE[23000]:完整性约束违反:19列邮件不是唯一的(SQL: update . SQL)"客人"…

该邮件不是唯一的,因为该邮件与我正在更新的邮件相同。在我尝试使用CommandBus之前,这从来没有给我一个问题。

当使用质量分配时,你必须在你的模型中声明一个$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属性。

问题是我实际上并没有更新一个现有的模型,所以当在一个新模型上调用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;
}