Answer the question
In order to leave comments, you need to log in
Laravel - Many To Many | With | How to get all data at once from all relations?
Table - Users
-----------------
ID - USERNAME
1. Arno
2. Hinker
Table - Articles
------------------
ID - TEXT
1. Simple Text
2. Second Text
3. Fifty Text
4. Final Text
Table - article_user
-----------------------
ID - USER_ID - ARTICLE_ID
1. 1 - 1
2. 1 - 2
3. 2 - 3
4. 2 - 4
I want to get all records that belong to users 1,2.
And after that I want to make WHERE for these records.
$users = User::whereIn('id', [1, 2]);
/*** FOR EXAMPLE ***/
$users->articles();
or
$users->with('articles');
The result should be like this
1. Simple Text
2. Second Text
3. Fifty Text
4. Final Text
Thank you very much
Answer the question
In order to leave comments, you need to log in
Everything is described in the doc :
Example:
// Retrieve all articles with at least one user where array of user id
$articles = Article::whereHas('users', function ($query) use ($users_id) {
$query->whereIn('id', $users_id);
})->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question