how do u define most used? is there another table or something? also if you put your raw SQL it would help people better understand what u want.
Eloquent 3 table query
Hey all, I'm new to Laravel and I hope someone can help me.
I have 3 tables
Users:
public function recipes() {
return $this->hasMany(Recipe::class);
}
}
Recipes:
public function category() {
return $this->belongsTo(Category::class);
}
}
And Category which has no relations
I want to display in my view for logged in user his most used recipe categories(each recipe belongs to one category), I know in raw sql but not in eloquent
Thanks
auth()->user() will get the currently logged-in user, you can work through the relationships from there:
You should set up the inverse relationship for the category model.
Category.php
public function recipes()
{
return this->hasMany(Recipes::class);
}
To do the query you can chain the relationships as such - using the with facade to include a recipes' category.
$user_id = auth()->user()->id;
$results = User::with('recipes.category')->where('id', $user_id)->get()
You could then do a groupBy() and then do a count.
$results->select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();
You could do it in one go, of course, but I tried to highlight each step.
Please or to participate in this conversation.