简体   繁体   中英

Laravel Eloquent Model - Appends with Join Query

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM