I have a Parent model with multiple Child models. The child models perform a calculation based a factor inside the parent model.
The factor can be changed by the user. I set the factor overwrite inside the controller, but the child classes don't get the altered parent object but the orignal from the database.
Models:
class Parent extends Model
{
public function childs()
{
return $this->hasMany('App\Child');
}
public function getFactorOverwriteAttribute($value) {
if (is_null($value)) {
return $this->factor;
}
return $value;
}
}
class Child extends Model
{
public function parent()
{
return $this->belongsTo('App\Parent');
}
public function getAmountAttribute($value)
{
// doesn't recognize `$parent->factor_overwrite = $user_value` in the controller.
return $value / $this->parent->factor * $this->parent->factor_overwrite;
}
}
Controller:
class ParentController extends BaseController
{
function show($id)
{
$parent = Parent::find($id);
if (request()->has('factor_overwrite')) {
$parent->factor_overwrite = request()->factor_overwrite;
}
// doesn't use the overwrite
dd($parent->childs->first()->amount);
}
}
Is there a best practice to hand down such a value? I'm using Laravel 5.4.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire