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

Man*_*ian 2 laravel eloquent laravel-5 laravel-5.3

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

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

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

我已经查看了touches属性,这会导致父进程的时间戳在子进程被修改时自动更新.但这仅适用于创建新关系时,而不适用于删除旧关系时.而且,这将更新任何字段更改时父级的时间戳,而不仅仅是<parent>_id那些我不想要的东西.

Oll*_*ell 14

取自Laravel 文档

触摸父时间戳

当模型belongsTobelongsToMany其他模型(例如Comment属于 a 的 a )时 Post,有时在更新子模型时更新父模型的时间戳会很有帮助。例如,当Comment模型更新时,您可能希望自动“触摸”updated_at拥有的 时间戳Post。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');
    } }
Run Code Online (Sandbox Code Playgroud)

现在,当您更新 a 时Comment,拥有Postupdated_at列也会更新,从而更方便地知道何时使Post模型的缓存无效:

$comment = App\Comment::find(1);

$comment->text = 'Edit to this comment!';

$comment->save();
Run Code Online (Sandbox Code Playgroud)

更新

模型上的删除方法确实更新所有者时间戳方法取自 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;
}
Run Code Online (Sandbox Code Playgroud)


geo*_*dri 9

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

$parent->touch(); //will update updated_at 
Run Code Online (Sandbox Code Playgroud)

如果我没有误解,我想不出一种方法来"自动"执行此操作,除非在需要时调用此内联或在子项上使用适当的Eloquent事件(例如,创建和删除或创建和删除)以进行触摸父母的时间戳.