gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:09:44 31 4
gpt4 key购买 nike

在 Laravel 中,模型具有 belongs to与另一个的关系,也有<parent>_id其表中指向 id 的字段 parent 的。当该模型与另一个模型关联时 updated_at timespamp 自然会更新,就像 <parent>_id 的值一样。字段更改。

父模型,即带有 has many 的模型关系,当它与子模型相关或不再相关时,没有任何字段会发生变化,因此它的 updated_at时间戳不会改变。

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

我已经研究过 touches属性,这会导致父级的时间戳在子级被修改时自动更新。但这仅在创建新关系时有效,而在删除旧关系时无效。而且,这将在任何字段更改时更新父级的时间戳,而不仅仅是 <parent>_id 的时间戳。这实际上并不是我想要的。

最佳答案

取自 Laravel Docs .

接触父时间戳

当一个模型belongsTobelongsToMany另一个模型时,例如属于PostComment,有时,在更新子模型时更新父模型的时间戳会很有帮助。例如,当更新 Comment 模型时,您可能希望自动“触摸”所属 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时,所属的Postupdated_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;
}

关于laravel - 创建或删除关系时如何自动更新父模型的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888153/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com