V
V
VoRoN19992022-02-12 17:43:04
Laravel
VoRoN1999, 2022-02-12 17:43:04

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'));
    }


and accordingly brought it to appends. Now the result of this method looks like this: {}

A working version that generates a bunch of requests:

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');
    }


How to implement this idea in one request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Maslov, 2022-02-14
@tmaslov22

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 question

Ask a Question

731 491 924 answers to any question