Answer the question
In order to leave comments, you need to log in
How to correctly add your own value to the model using join?
I use Laravel 6.
In the model I created the following:
public function getCountPointsAttribute()
{
return $this->query()
->join('coefficients as k1', 'event_id', '=', 'k1.id')
->join('coefficients as k2', 'participation_id', '=', 'k2.id')
->join('coefficients as k3', 'individuality_id', '=', 'k3.id')
->select(DB::raw('round(sum(k1.coefficient * k2.coefficient * k3.coefficient), 1) as points'));
}
public function getCountPointsAttribute()
{
$sum = $this->getEvent->coefficient
* $this->getParticipation->coefficient
* $this->getIndividuality->coefficient;
return round($sum, 1);
}
public function getEvent()
{
return $this->hasOne(Coefficient::class, 'id', 'event_id');
}
public function getParticipation()
{
return $this->hasOne(Coefficient::class, 'id', 'participation_id');
}
public function getIndividuality()
{
return $this->hasOne(Coefficient::class, 'id', 'individuality_id');
}
Answer the question
In order to leave comments, you need to log in
Now getCountPointsAttribute is preparing a query (Query Builder) rather than returning a value. It is worth adding a function to call this query and get the value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question