【问题标题】:How to let Laravel pivot table use only created_at?如何让 Laravel 数据透视表只使用 created_at?
【发布时间】:2019-12-07 09:08:11
【问题描述】:

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

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

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

class Foo extends Model
{
    public function bars() {
        $this->belongsToMany(Bar::class)->withTimestamps();
    }
}

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

【问题讨论】:

    标签: php laravel laravel-5 eloquent relationship


    【解决方案1】:

    你可以采取另一种方法:

    • 跳过withTimestamps() 方法(以避免同时添加created_atupdated_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 - 这与 Laravel 对时间戳列所做的相反 - 所以:

    $foo->bars()->first()->pivot->created_at
    

    不会是Carbon 的实例。如果你想要它,you could create a custom Pivot model,然后指定 the column to cast 并更新你的关系以使用自定义 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');
    //                                       ^^^^^^^^^^^^^^^^^^^^
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2018-04-10
      • 1970-01-01
      • 2023-03-16
      • 2013-03-27
      • 1970-01-01
      相关资源
      最近更新 更多