Answer the question
In order to leave comments, you need to log in
How to get the number of entities related to relationships?
There are links, for example:
- Posts
- Categories of posts
- Users
Let's say a moderator can give access to users to publish their posts in certain categories.
Database
categories
- id
- name
users
- id
- name
user_categories
- user_id
- category_id
posts
- id
- user_id
- category_id
- title
- description
$query = Users::query()->with([
'categories' => function (BelongsToMany $relation) {
$relation->withCount(['posts' => function (Builder $builder) {
// ...
}]);
}
]);
Answer the question
In order to leave comments, you need to log in
Decision
$query = Users::query()->with([
'categories' => function (BelongsToMany $relation) {
$relation->withCount(['posts' => function (Builder $builder) {
$builder->whereRaw("`post`.`user_id` = `user_categories`.`user_id`");
}]);
}
]);
Not sure, but can be added to the model Categories
/**
* Получить все посты для пользователя.
*/
public function usersPosts()
{
return $this->hasManyThrough('App\User', 'App\Post');
}
To execute this query, Eloquent looks up the catalog_id in the posts intermediate table. After matching post IDs are found, they are used in the query against the users table.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question