问题描述
我正在使用Laravel 8,在我的应用程序中,我与一个自定义模型具有属于许多关系",我想删除"updated_at"字段.
关系
公共功能tracks(){返回$ this-> belongsToMany(Track :: class)->使用(CollectionTrack :: class)-> withPivot('sort','created_at','id');}
自定义模型
class CollectionTrack扩展了Pivot{使用Sortable;公共常量UPDATED_AT = null;public $ incrementing = true;公共静态函数enableAutoSort(){返回false;}}
问题是,当我想同步时,它会尝试填充 updated_at
字段.
但是,我使用下面的代码从模型中删除了updated_at.
public const UPDATED_AT = null;
而且,仅在 withPivot
中获得created_at.
当我从withPivot中删除 created_at
时,问题就消失了,但是在那种情况下,当我检索数据时 created_at
不会出现在字段中./p>
注意:我的目标是禁用 updated_at
时间戳,并且只具有 created_at
,因此当我附加新记录时,将created_at设置为当我检索它时,模型具有这些枢纽字段'sort','created_at','id.'
我认为您可以从迁移中删除 $ table-> timestamps()
,而只需添加一个字段 created_at
具有默认值的当前时间戳记.
$ table-> timestamp('created_at')-> default(DB :: raw('CURRENT_TIMESTAMP'));
我猜应该可以工作.
还有另外一个答案,您可以参考.
I'm using Laravel 8 and in my application, I have Belongs to Many relations with a custom model, and I want to remove the 'updated_at' field.
Relation
public function tracks()
{
return $this->belongsToMany(Track::class)
->using(CollectionTrack::class)
->withPivot('sort' , 'created_at' , 'id');
}
Custom model
class CollectionTrack extends Pivot
{
use Sortable;
public const UPDATED_AT = null;
public $incrementing = true;
public static function enableAutoSort () {
return false;
}
}
The issue is that when I want to sync, it tries to fill the updated_at
field.
However, I removed the updated_at from the Model using the following line.
public const UPDATED_AT = null;
And also, only get the created_at in withPivot
.
When I remove the created_at
from withPivot, the issue goes away, but in that case, when I retrieve the data created_at
won't be in the fields.
Note: my goal is to disable the updated_at
timestamp and only have created_at
so when I attach a new record, the created_at set and when I retrieve it, the model has these pivot fields 'sort', 'created_at', 'id.'
I think you can remove $table->timestamps()
from your migration and just add a field created_at
having default value current time stamp.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
should work I guess.
There is another answer you can refer.
这篇关于使用不带' updated_at'的自定义中间表模型的雄辩的多对多关系场地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!