如何让 Laravel 数据透视表只使用 created_at?

在处理belongsToMany 关系时,您使用数据透视表来记录关系。


对于许多数据透视表,关系只是创建然后删除。他们不会有自己的财产,所以你永远不会更新他们。


我知道我可以这样做来自动设置 updated_at 和 created_at。


class Foo extends Model

{

    public function bars() {

        $this->belongsToMany(Bar::class)->withTimestamps();

    }

}

但是如何只使用 created_at 呢?我不知道。


潇湘沐
浏览 127回答 1
1回答

暮色呼如

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