samedi 12 mars 2016

Laravel , getting count of an attribute

I have a table called Vote, and another table called sub_item. Vote and sub_item share a one to many relationship. I have another table called Vote_casts, which records which sub item the user cast a vote on. This is an example of it:

Now, I want to calculate what the number of votes on each sub_item for a particular vote is. I am not storing this value, as it would denormalise the table. Instead, I wish to calculate this data from the vote_casts table. (by calculating the count of the rows for a particular sub_item_id, i will be able to do so).

So in my Model, I created this :

public function getCountAttribute(){

    return Vote_cast_action::where('sub_item_id',$this->id)->count();

}

This works as expected. But the problem is, for each sub item in a vote, the query is called. So if there are 20 sub items in a vote, this line itself will be called 20 times (I am saying this after looking at my sql query log)

Is there a way to make this query more efficient in laravel ? enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire