简体   繁体   English

在Laravel中使用mutator来填充列

[英]Using mutator in Laravel to populate column

I have a column in my booking model which stores datetime as reservation_datetime , however in my forms I have split this into two separate fields (date & time html5 inputs). 我在预订模型中有一个列,它将datetime存储为reservation_datetime ,但是在我的表单中,我将其拆分为两个单独的字段(日期和时间html5输入)。

I have created a setter mutator to store date derived from the two inputs, however nothing is saved into the reservation_datetime column when the record is inserted. 我创建了一个setter mutator来存储从两个输入派生的日期,但是在插入记录时没有保存到reservation_datetime列中。

This is my mutator 这是我的变异者

public function setReservationDatetimeAttribute($value)
{
    return $this->attributes['reservation_datetime'] = $this->date . " " . $this->time;
}

I've noticed that if I put pseudo inputs into my $fillable array ( reservation_datetime is already present) then I am able to set the mutator to the correct value but this causes other issues where the ORM is trying to save date and time columns which obviously doesn't exist causing an error on save. 我注意到,如果我将伪输入放入我的$fillable数组( reservation_datetime已经存在),那么我可以将mutator设置为正确的值,但这会导致ORM尝试保存datetime列的其他问题显然不存在导致保存错误。

Mutators are the wrong tool for this. Mutators是错误的工具。 Set reservation_datetime manually in your controller. 在控制器中手动设置reservation_datetime

Mutators are meant to be used the other way around. 突变体意味着反过来使用。 For example if your form has a single field that you want to split in two, or to simply mutate the value of a single attribute. 例如,如果表单具有要分割为两个的单个字段,或者只是改变单个属性的值。

Combining two attributes into one is simply not what mutators are about. 将两个属性合二为一,根本不是变换器的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM