gpt4 book ai didi

php - 更新附加/分离 Eloquent 关系的时间戳

转载 作者:可可西里 更新时间:2023-10-31 22:54:21 25 4
gpt4 key购买 nike

我正在使用 Laravel 4,并且有 2 个模型:

class Asset extends \Eloquent {
public function products() {
return $this->belongsToMany('Product');
}
}

class Product extends \Eloquent {
public function assets() {
return $this->belongsToMany('Asset');
}
}

Product上面有标准时间戳( created_atupdated_at ),我想更新 updated_at Product 的领域当我附加/分离一个 Asset .

我在 Asset 上试过这个型号:

class Asset extends \Eloquent {
public function products() {
return $this->belongsToMany('Product')->withTimestamps();
}
}

...但这根本没有任何作用(显然)。 编辑:显然这是为了更新数据透视表上的时间戳,而不是为了更新关系自己的表上的时间戳(即更新 assets_products.updated_at ,而不是 products.updated_at )。

然后我在 Asset 上尝试了这个型号:

class Asset extends \Eloquent {
protected $touches = [ 'products' ];

public function products() {
return $this->belongsToMany('Product');
}
}

...这有效,但随后破坏了我调用 Asset::create([ ... ]); 的种子因为显然 Laravel 试图调用 ->touchOwners()在关系上而不检查它是否是 null :

PHP Fatal error: Call to undefined method Illuminate\Database\Eloquent\Collection::touchOwners() in /projectdir/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 1583

我用来添加/删除的代码 Asset这是:

Product::find( $validId )->assets()->attach( $anotherValidId );
Product::find( $validId )->assets()->detach( $anotherValidId );

我哪里错了?

最佳答案

您可以使用 touch 方法手动完成:

$product = Product::find($validId);
$product->assets()->attach($anotherValidId);
$product->touch();

但是,如果您不想每次都手动执行此操作,您可以通过以下方式在 Product 模型中简化此创建方法:

public function attachAsset($id)
{
$this->assets()->attach($id);
$this->touch();
}

现在你可以这样使用它了:

Product::find($validId)->attachAsset($anotherValidId);

您当然可以对分离操作执行相同的操作。

我注意到你有一个关系 belongsToMany 和另一个 hasMany - 两者都应该是 belongsToMany 因为它是多对多关系

编辑

如果你想在许多模型中使用它,你可以创建特征或创建另一个基类来扩展 Eloquent,方法如下:

public function attach($id, $relationship =  null)
{
$relationship = $relationship ?: $this->relationship;
$this->{$relationship}()->attach($id);
$this->touch();
}

现在,如果您需要此功能,您只需从另一个基类扩展(或使用特征),现在您可以向您的 Product 类添加一个额外的属性:

private $relationship = 'assets';

现在你可以使用:

Product::find($validId)->attach($anotherValidId);

Product::find($validId)->attach($anotherValidId, 'assets');

如果您需要通过更新 updated_at 字段附加数据。当然你需要重复分离。

关于php - 更新附加/分离 Eloquent 关系的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781668/

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