Reputation: 3857
I have a Categories table.
It has a foreign key of question_category in the questions table
I am looping through 4 of my Categories like so :
$categories = MockCategories::take(4)->get();
In the MockCategories Model, I'd like to add a "num_questions" property. Which in turn will run a query in the questions table and return a count of number questions based on that category.
Can I do this? Is there maybe a better way of doing it? I'm thinking maybe adding a relationship of hasMany and linking to the questions, Then showing a count of them.
Any help appreciated.
Thanks
Upvotes: 1
Views: 422
Reputation: 32354
You can do something like this in the MockCategories model:
private $num_questions = 4;
public function scopeTakeFour($query) {
$query->take($this->num_questions )->get();
}
and in your controller you simply do:
MockCategories::takeFour();
Upvotes: 1