I'm having a bit of trouble making this work properly when querying with Eloquent, here's the model in question and my problem below:
class Category extends Model {
public function parent()
{
return $this->belongsTo('Category', 'parent_id', 'id');
}
public function subCategories()
{
return $this->hasMany('Category', 'parent_id', 'id');
}
}
Basically, each Category can have subCategories and/or be a parent Category to other Categories.
I'm pretty sure the additional params for belongsTo and hasMany are properly set, although I have tested with other combinations with no success. The 'categories' table has an 'id' and a 'parent_id' fields.
I'm having problems when querying for Categories like so:
$categories = Category::where('parent_id', '=', null)->get(); // this works!
$categories = Category::has('parent')->get(); // this gives me an empty collection - why?
Also, I've been trying to query for Categories with a specific parent Category (via slug):
$subCategories = Category::whereHas('parent', function($query) use ($categorySlug)
{
$query->where('slug', '=', $categorySlug);
})->get();
but also getting an empty collection, even though it should not be so (I've checked DB data several times).
Am I doing something wrong?
Try this
$cat = Category::where('parent_id', '=', null)->get()
$cat_kids = $cat->subCategories();
$cat_parent = $cat->parent();
Fetching subCategories and the parent category from already built model objects works fine, the problem is querying as I've described above.
has and whereHas are used to check if there exist at least one related model looking from the One-side to the Many-side.
Check out the generated query. You will understand the error.
At the moment I can not think of an easy solution
Category::whereNotNull('parent_id')->get();
That should do it. As for the other part of the question...writing this off the top of my head so it might need adjusting:
Category::select(DB::raw('pr_category.*, (select c2.slug from pr_category AS c2 where c2.id = pr_category.parent_id) as parentSlug'))->whereNotNull('parent_id')->where('parentSlug', $parentSlug)->get();
'pr_' being whatever your prefix is. Disclaimer: this might not work xD
Hi,
Was this ever solved. Attempting now and just want to be sure.
Thanks
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community