Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

First what comes to mind is just $user->badges()->recipes. Have you tried that?

0

Hey Xum, thanks for your answer! If I try that it says "Undefined property: lluminate\Database\Eloquent\Relations\BelongsToMany::$recipes"

Also I already filter the recipes beforehand. I would like to concatenate the filter descriped above to the previous ones. Therefore, it would be very helpful if the solution does not start with $user. I want something like this: $recipes->...

0

joneswack said:

MY PROBLEM I am trying to filter the recipes table so that the recipe's badges match the user's badges. So the Recipe Model as well as the User Model have a belongsToMany('Badge') relation.

Your controller filter the recipes table

So you can use in badge Model

public function recipes()
{
	return $this->belongsToMany('Recipe');
}

UserModel

public function badges()
{
	return $this->belongsToMany('Badge');
}

Then you can user

foreach($user->badges()->recipes as $recipe){
	......
}
0

@joneswack, Yes, you need to define relations first, like in @tuyenlaptrinh's post.

And chain your filters to that expression:

$recipes = $user->badges()->recipies()->where('this', '=', 'that')->orWhere('yumminess', '>=', '9000')->get();
Last updated 8 years ago.
0

Hey guys, thanks for your answers. I am sure they work, too. But I needed something that could be concatenated to my previous filters. I had a few recipes already which needed to be filtered again. Therefore the command should start with recipe->...

I found the following solution that seems to work fine:

Recipe::join('badge_recipe as br', 'br.recipe_id', '=', 'recipes.id') ->join('badge_user as bu', 'bu.badge_id', '=', 'br.badge_id')->where('bu.user_id', '=', Auth::user()->id);

0

Sign in to participate in this thread!

Eventy

Your banner here too?

joneswack joneswack Joined 2 May 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.