首页 文章

如何在创建或删除关系时自动更新父模型的时间戳?

提问于
浏览
1

在Laravel中,与另一个关系具有 belongs to 关系的模型,其表上还有一个 <parent>_id 字段,指向父级的 id . 当该模型与另一个模型相关联时, updated_at timespamp会自然更新,因为 <parent>_id 字段的值会发生变化 .

但是,父模型(具有 has many 关系的父模型)在变为或停止与子模型相关时没有任何更改的字段,因此其 updated_at timespamp不会更改 .

我想要的是,每次创建或删除两者之间的关系时,父模型和子模型都会自动更新它们的 updated_at 次浮点数 . 实现这个目标的正确方法是什么?

我已经查看了touches属性,这会导致父级的时间戳在子级被修改时自动更新 . 但这仅适用于创建新关系时,而不适用于删除旧关系时 . 而且,这将更新任何字段更改时父级的时间戳,而不仅仅是 <parent>_id 和's something that I don'实际需要的字段 .

2 回答

  • 6

    您可以使用Eloquent提供的touch方法来更新父级的updated_at时间戳 .

    $parent->touch(); //will update updated_at
    

    如果我没有想到"automatically"这样做的方法,除非在需要时调用此内联或在子项上使用适当的Eloquent Events(例如创建和删除或创建和删除)以触摸父级的时间戳 .

  • 3

    取自Laravel Docs .

    触摸父时间戳

    当模型 belongsTobelongsToMany 另一个模型(例如属于 PostComment )时,更新子模型时更新父级的时间戳有时会很有帮助 . 例如,更新 Comment 模型时,您可能希望自动"touch"拥有 Postupdated_at 时间戳 . Eloquent让事情变得简单 . 只需将包含关系名称的 touches 属性添加到子模型:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Comment extends Model {
    
        /**
         * All of the relationships to be touched.
         *
         * @var array
         */
         protected $touches = ['post'];
    
        /**
         * Get the post that the comment belongs to.
         */
        public function post()
        {
            return $this->belongsTo('App\Post');
        } }
    

    现在,当您更新 Comment 时,拥有的 Post 也会更新其 updated_at 列,这样可以更方便地知道何时使 Post 模型的缓存无效:

    $comment = App\Comment::find(1);
    
    $comment->text = 'Edit to this comment!';
    
    $comment->save();
    

    更新

    模型上的删除方法确实更新了所有者时间戳方法取自Illuminate \ Database \ Eloquent \ Model.php

    要手动更新,您可以运行 $this->touchOwners();

    public function delete()
    {
        if (is_null($this->getKeyName())) {
            throw new Exception('No primary key defined on model.');
        }
    
        // If the model doesn't exist, there is nothing to delete so we'll just return
        // immediately and not do anything else. Otherwise, we will continue with a
        // deletion process on the model, firing the proper events, and so forth.
        if (! $this->exists) {
            return;
        }
    
        if ($this->fireModelEvent('deleting') === false) {
            return false;
        }
    
        // Here, we'll touch the owning models, verifying these timestamps get updated
        // for the models. This will allow any caching to get broken on the parents
        // by the timestamp. Then we will go ahead and delete the model instance.
        $this->touchOwners();
    
        $this->performDeleteOnModel();
    
        $this->exists = false;
    
        // Once the model has been deleted, we will fire off the deleted event so that
        // the developers may hook into post-delete operations. We will then return
        // a boolean true as the delete is presumably successful on the database.
        $this->fireModelEvent('deleted', false);
    
        return true;
    }
    

相关问题