Reputation: 1256
I have an issue retrieving objects using the ->with()
method of a Model object.
In my app, I have 4 tables (I write here what I think is the essential fields of my table, so ):
**Categories**:
id
**Subcategorie**
id
id_categorie
**UserSubcategorie**
id_user
id_subcategorie
**Lawyers**
user_id
I'm trying to get all the users for a given Categorie (which means all the users connected to all the categorie's subcategorie)
My request is as followed :
$categorie = LegalCategory::whereIn('id', $arrayCat)->with('legal_subcategories')->get();
foreach ($categorie as $k =>$cat){
$selectedCat[$k]['categorie'] = $cat;
$selectedCat[$k]['lawyers'] =
Lawyer::Join('lawyers_legal_subcategories', 'lawyers.user_id', '=', 'lawyers_legal_subcategories.user_id')
->with('lawyer_subcategories')
->whereIn('lawyers_legal_subcategories.legal_subcategory_id', $cat->legal_subcategories)
->get();
}
I'm getting the Lawyers correctly but when I look into lawyer->legal_subcategories
, I have NULL
I don't understand why because when I try this :
Lawyer::orderBy('created_at')->take(4)->with('lawyer_subcategories')->get()
I have my subcategories in the Lawyer object.
Does someone has an idea about what the issue could be ?
Upvotes: 1
Views: 28
Reputation: 1288
You should learn how to use has many through and Eager Loading. This will make you life easier.
On your case, you are making a lot of query, which will make your database suffer in the long run. Eager loading and Laravel eloquent provide a very efficient features to handle those kind of cases.
If you defined your model correctly, you retrieve all your needed data using with() method.
Upvotes: 1
Reputation: 11083
The problem is in this line :
->whereIn('lawyers_legal_subcategories.legal_subcategory_id', $cat->legal_subcategories)
you need to pass array of IDs not all the subcategories !
$categorie = LegalCategory::whereIn('id', $arrayCat)
->with('legal_subcategories')
->get();
foreach ($categorie as $k =>$cat){
$selectedCat[$k]['categorie'] = $cat;
$selectedCat[$k]['lawyers'] =
Lawyer::Join('lawyers_legal_subcategories', 'lawyers.user_id', '=', 'lawyers_legal_subcategories.user_id')
->with('lawyer_subcategories')
->whereIn('lawyers_legal_subcategories.legal_subcategory_id',
$cat->legal_subcategories->pluck('id'))
->get();
}
Upvotes: 1