我尝试在观察者中使用 updateOrCreate 函数。 所以我有这个功能:
$transportpropremoyenaller = Transport::updateOrCreate(
['centre_id' => $gestionsejour->centre_id, 'allerouretour' =>
'Aller', 'date' => $gestionsejour->datedebut],
['ville' => \Config::get('constants.transport.0'), 'tarif' => '0']
);
我在 GestionsejourObserver 中使用这个函数,如下所示:
public function created(Gestionsejour $gestionsejour)
{
return $this->addtransportpropremoyen($gestionsejour);
}
当我创建一个新对象时 updateOrCreate 永远不会更新并始终创建一个新对象。
Gestionsejour 模型是:
protected $fillable = [
'datefin',
'user_id',
'agrement',
'centre_id',
'datedebut',
'created_at',
'updated_at',
'deleted_at',
'dureesejour',
'periodesejour',
'complet',
];
public function centre()
{
return $this->belongsTo(Centre::class, 'centre_id');
}
public function getDatedebutAttribute($value)
{
return $value ? Carbon::parse($value)->format(config('panel.date_format')) : null;
}
public function setDatedebutAttribute($value)
{
$this->attributes['datedebut'] = $value ? Carbon::createFromFormat(config('panel.date_format'), $value)->format('Y-m-d') : null;
}
public function getDatefinAttribute($value)
{
return $value ? Carbon::parse($value)->format(config('panel.date_format')) : null;
}
public function setDatefinAttribute($value)
{
$this->attributes['datefin'] = $value ? Carbon::createFromFormat(config('panel.date_format'), $value)->format('Y-m-d') : null;
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Myabe 无法发送 3 个属性或日期有问题。我不知道。我正在阅读 laravel 文档,但不明白这个简单函数有什么问题。
我认为你的问题就出在这个方法上
getDatedebutAttribute
当您运行以下代码时,还会使用访问器,这意味着您正在搜索 d-m-y 格式,如下所示。
'date' => $gestionsejour->datedebut // '03-08-2019' <- because of getDatedebutAttribute
也许您可以创建一个辅助方法,而不是使用访问器和修改器。使模型上的数据与数据库中的数据相同。 您可以在模型上做的另一件事是告诉哪些列是带有 $dates 的日期,因此它们将自动成为 Carbon 对象
// Model.php
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'datedebut',
];
public function formattedDateDebut()
{
return $this->datedebut ? $this->datedebut->format('d-m-y') : null;
}
并像这样在你的视图中使用它。
{{ $gestionsejour->formattedDateDebut() }}
这样你也不再需要
setDatedebutAttribute
了,因为Y-m-d是你在这里使用它时的默认格式'date' => $gestionsejour->datedebut
更好的是:你可以考虑这样的事情。
public function setTypeAttribute($value) {
$typeVal = array_search($value, self::TYPE);
if ($typeVal === false)
$typeVal = $value;
$this->attributes['type'] = $value;
}
您将需要绕过突变,因为这是 updateOrCreate 幕后发生的事情:
public static function updateOrCreate($where, $fields) {
$record = self::where($where)->first();
if ($record) {
$record->update($fields);
}
else
$record = self::create(array_merge($where, $fields));
return $record;
}
请注意,对于$where,不应该有突变,但是对于$fields,它会在到达数据库之前发生突变,当您合并$where和$fields时,就会出现问题,您将未突变的值混合到$fields中.
或者解决方案 2,将预变异值附加到 updateOrCreate() 的第二个参数。例如。
updateOrCreate(['date' => $mutatedValue], [
'date' => $premutatedValue
])
希望有帮助。