【问题标题】:update parent timestamps when updating child model in polymorphic relationship更新多态关系中的子模型时更新父时间戳
【发布时间】:2015-08-30 19:29:04
【问题描述】:

在 Laravel 5.1 中,我有两个模型。一个城市模型和一个照片模型。
City 和 Photo 之间存在多态关系。 使用

更新城市照片时
$city->photos()->updateOrCreate($attributes,$values)

子时间戳更新。但是父模型的时间戳,在这种情况下是 City,没有相应更新,我应该手动调用

$city->touch()

在 Laravel 中触摸子模型时如何更新父模型的时间戳?

【问题讨论】:

  • 如果您希望数据透视表自动维护 created_at 和 updated_at 时间戳,请在关系定义上使用 withTimestamps 方法: return $this->belongsToMany('App\Role')->withTimestamps() ;
  • 我很想知道您喜欢这种行为的原因?谢谢

标签: laravel polymorphism eloquent laravel-5.1


【解决方案1】:

对于多态关系

class Photo extends Eloquent {

  protected $touches = ['city'];

  public function city() {
    return $this->morphTo() // add this function if not already done
  }
}

class City extends Eloquent {

  public function photos() {
    return $this->morphMany(App\Photo::class, 'city');
  }
}

在这种情况下,当照片更新时,它会触及他的父母(在那种情况下是城市)。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    要更新父级的时间戳:

    在您的 Photo.php 模型中,您可以声明以下行:

    class Photo extends Model
    {
       protected $touches = ['city']; //The 'city' refers to your parent's model
    }
    

    现在,当您像以前那样更新照片模型时:

    $city->photos()->updateOrCreate($attributes,$values)
    

    它会自动更新你父母的模型的时间戳,在你的例子中,城市表。

    【讨论】:

    • 您能发布您的型号代码吗?我做过类似的案例,它有效。请参阅此文档,了解如何在更新子 laravel.com/docs/5.0/eloquent#touching-parent-timestamps 时更新父时间戳
    • 只需将您的答案从“照片”更改为“照片”。它应该参考孩子的模型。这也适用于模型belongsto另一个模型的关系。我有一个多态关系。
    • nope :) 我只是手动触摸模型。测试了您的答案,但没有帮助。无论如何,谢谢你
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多