1 回答
TA贡献1853条经验 获得超9个赞
你可以采取另一种方法:
跳过该withTimestamps()方法(以避免同时添加created_at和updated_at列)。
添加自定义数据透视列:created_at。
所以你的代码:
class Foo extends Model
{
public function bars() {
$this->belongsToMany(Bar::class)->withPivot('created_at');
} // ^^^^^^^^^^^^^^^^^^^^^^^^
}
现在,使用这种方法,您需要created_at在创建记录时手动设置值:
$foo = Foo::find(1);
$foo->bars()->attach($someId, ['created_at' => now()->format('d-m-Y H:i:s')]);
// or whatever you use as date ^^^^^^^^^^^^^
此外,Date默认情况下,此列不会被转换为 a - 与 Laravel 对时间戳列所做的相反 - 所以这个:
$foo->bars()->first()->pivot->created_at
不会是Carbon的实例。如果需要,您可以创建自定义 Pivot 模型,然后指定要转换的列并更新您的关系以使用自定义 Pivot 模型:
枢轴模型 FooBar.php
class FooBar extends Pivot // <--
{
protected $casts = [
'created_at' => 'datetime:d-m-Y H:i:s',
];
}
然后在你的Foo.php课堂上:
class Foo extends Model
{
public function bars() {
$this->belongsToMany(Bar::class)->using(FooBar::class)->withPivot('created_at');
// ^^^^^^^^^^^^^^^^^^^^
}
}
- 1 回答
- 1 关注
- 126 浏览
添加回答
举报