I have the users
, promocodes
and users_promocodes
tables. Models: User
, Promocode
and UserPromocode
.
They are the keys of users_promocodes
table: 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
?
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:
<?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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.