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