[英]Laravel mass change Eloquent
I have the users
, promocodes
and users_promocodes
tables. 我有
users
, promocodes
和users_promocodes
表。 Models: User
, Promocode
and UserPromocode
. 型号:
User
, Promocode
和UserPromocode
。
They are the keys of users_promocodes
table: user_id
-> users.id
, promocode_id
-> promocodes.id
他们的钥匙
users_promocodes
表: user_id
- > users.id
, promocode_id
- > promocodes.id
And when I delete the promocode from base, I need to take away the promocode bonus. 当我从基本删除促销代码时,我需要拿走促销代码奖励。 How can I set by Eloquent
users.bonus
( users.bonus - 5
) value for users, who have the users_promocodes.id = 10
? 我如何通过雄辩的
users.bonus
( users.bonus - 5
)值来为具有users_promocodes.id = 10
用户设置值?
I would use Model Observers to track these kind of changes. 我将使用模型观察器来跟踪此类更改。
When PromoCodes are deleted, you can query on the users
table and update as needed: 删除PromoCodes后,您可以在
users
表上查询并根据需要进行更新:
<?php
namespace App\Observers;
class PromoCodeObserver
{
/**
* Listen to the PromoCode Deleting event.
*
* @param PromoCode $promoCode
* @return void
*/
public function deleting(PromoCode $promoCode)
{
// search for all users associated with the promo code
// update the bonus and save changes
$promoCode->users->each(function (User $user) {
$user->update(['bonus' => $user->bonus - 5]);
});
}
}
// User.php
public function promocode()
{
return $this->belongsTo(PromoCode::class);
}
// PromoCode.php
public function users()
{
return $this->hasMany(User::class);
}
Assuming a User can only have one PromoCode you'll need the above one-to-many relationship, just add a promo_code_id
field on users
if that is the case. 假设一个用户只能有一个PromoCode,则需要上述一对多关系,如果是这样,只需在
users
上添加一个promo_code_id
字段即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.