E
E
Eugene2018-03-03 13:23:49
MySQL
Eugene, 2018-03-03 13:23:49

How to select tags and count the number of articles in Laravel?

Hello!
Please tell me the best solution for the following problem.
There is a list of tags (about 2000). We need to display a list of tags on the page indicating the number of articles attached to them using Laravel Query Builder.
There are no problems with the selection of tags. And what needs to be added in order to also get the number of materials in the content table , where content.tag_id is equal to tags.tag_id . Thank you!
$request = DB::table('tags')->paginate(150);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
anlamas, 2018-03-05
@nimfai

1. Set up relationships
Usually, for tags, they work with Many To Many or Many To Many Polymorphic Relations
2. Now you need to write relationships queries The number of articles is stored in the contents_count field If you want to filter articles, then

$tags = App\Tag::withCount(['contents' => function ($query) {
    $query->where('status', 1);
}])->get();

M
Mokhirjon Naimov, 2018-03-03
@zvermafia

Please tell me the best solution for the following problem.

Database: Query Builder

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question