首页 文章

在多态关系中更新子模型时更新父时间戳

提问于
浏览
2

在Laravel 5.1我有两个模型 . 一个城市模型和一个照片模型 .
城市和照片之间存在多态关系 . 用更新城市的照片时

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

孩子时间戳更新 . 但是父模型的时间戳(在这种情况下是City)不会相应更新,我应该手动调用

$city->touch()

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

2 回答

  • 2

    对于多态关系

    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');
      }
    }
    

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

    希望能帮助到你 .

  • 0

    要更新父级的时间戳:

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

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

    现在,当您更新照片模型时,就像您所做的那样:

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

    它将自动更新父级模型的时间戳,在您的情况下,城市表 .

相关问题