This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
xyz.qtc63355
In order to use model attribute you need to save (create) the model first. Why?
I have a TOTAL AMOUNT field which is updated (depends on) when I add a new product to a list of products (relation hasMany) in my model.
This is how I update my total amount field:
public function filterFields($fields, $context = null)
{
$fields->total->value = $this->total;
}
public function getTotalAttribute()
{
$totale = 0;
foreach ($this->orderitems as $orderitem => $value) {
$totale += $value->total;
}
return $totale;
}
So simply, until I save the new object, I cannot use the models attributes $this->orderitems, $this->total etc.
Last updated
mjauvin
Until the parent model is saved, its relations are deferred... so use the withDeferred()
method to access the deferred relations:
public function getTotalAttribute()
{
$totale = 0;
$sessionKey = post('_session_key');
if ($sessionKey) {
foreach ($this->orderitems()->withDeferred($sessionKey)->get() as $orderitem => $value) {
$totale += $value->total;
}
}
return $totale;
}
1-2 of 2