Laravel手动更新时间戳返回null

时间:2018-01-30 08:42:32

标签: php mysql laravel model timestamp

我有一些孩子的报价。

我希望在父级expire_time字段更改时更新每个子节点的expire_time字段。

但它返回null。

expire_time类型是时间戳。

这是我在模型中的代码:

if ($offer->childrenOffers->count()) {
        $offer->childrenOffers->each(function (self $childOffer) use($offer) {

            ddd($offer->expire_time); //returns "2018-02-30 23:59:59"
            ddd($childOffer->expire_time); //returns "2018-02-01 23:59:59"

            $childOffer->expire_time = $offer->expire_time;

            dd($childOffer->expire_time); //returns null

            $childOffer->save();
        });
    }

我该怎么做?!

3 个答案:

答案 0 :(得分:2)

expire_time添加到模型中的可填写字段,并确保保留到数据库,然后检查

if ($offer->childrenOffers->count()) {

    $offer->childrenOffers->each(function (self $childOffer) use($offer) {
       $childOffer->expire_time = $offer->expire_time;     
       $childOffer->save();
       dd($childOffer->expire_time); //returns null    
    });
}

答案 1 :(得分:2)

使用savedupdated Eloquent events

每当您更新模型时,您都可以更新其子项。

答案 2 :(得分:0)

您可以使用Eloquent Event

  

Eloquent模型可以触发多个事件,允许您在模型的生命周期中隐藏以下几点:检索,创建,创建,更新,更新,保存,保存,删除,删除,恢复,恢复。事件允许您在每次在数据库中保存或更新特定模型类时轻松执行代码。

在您Offer模型中,您可以添加引导方法,以便在保存或更新商品时自动更新子项,如下所示:

public static function boot() {
    parent::boot();

    //When the offer is updated
    static::updated(function ($offer) {
        $offer->childrenOffers->each(function ($child) use ($offer){
            $child->expire_time = $offer->expire_time;
            $child->save();
        });
    });
}