在我的一个模型中,当更新同一模型中的其他两个属性时,我需要更新另一个属性。
就我而言,使用 Accessor
不是一种选择,因为在某些情况下,我需要执行数据库查询来查找 full_phone_number
。
什么是达到预期结果的最佳方法?
这是我的模型:
class Address extends Model {
protected $fillable = [
'country_code',
'phone_number',
'full_phone_number',
];
}
当我创建新的地址
时,我需要自动填充full_phone_number
列:
$address = Address::create([
'country_code' => 55,
'phone_number' => 1199999999
]);
预期结果是:
# Address model on DB
{
"country_code": 55,
"phone_number": 1199999999,
"full_phone_number": 551199999999
}
当我从 Address
更新 country_code
或 phone_number
时,我需要自动更新 full_phone_number
列:
$address->update([
'phone_number' => 1188888888
]);
预期结果是:
# Address model on DB
{
"country_code": 55,
"phone_number": 1188888888,
"full_phone_number": 551188888888
}
最佳答案
我使用事件
获得了所需的结果,但我不知道这是否是处理这种情况的最佳方法。同样可以转换为观察者
。
class Address extends Model {
protected $fillable = [
'country_code',
'phone_number',
'full_phone_number',
];
protected static function boot()
{
parent::boot();
static::updating(function ($address) {
$address->full_phone_number = $address->country_code . $address->number;
});
}
}
关于php - Laravel - 更新模型时更新另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69621751/