Hardist
Hardist

Reputation: 1993

Laravel grab related models based on tags

I have two models, Expense and Tag, which have a Many to Many relation.

For each Expense, I can add multiple tags, which are stored in a pivot table using sync. The table is called expense_tag.

Now on my expenses.show page, I want to display details about one expense, obviously. But, I want to show ALL related expenses, using the tags relationship.

The problem:

I only have the information for one expense. Which means, I need to collect all tags that are assigned to that expense, and then using those tags, grab all expenses that were assigned one or more of those tags as well.

I want to refrain from having to use foreach loops to accomplish this. I've been trying with filter but I am unsure how to go about it. I just prefer keeping it simple.

Any suggestions for this?

My relations in my model:

Expense:

public function tags()
{
    return $this->belongsToMany(Tag::class);
}

Tag:

public function expenses()
{
    return $this->belongsToMany(Expense::class);
}

Upvotes: 1

Views: 28

Answers (1)

Thijs Steel
Thijs Steel

Reputation: 1272

The solution is to use a where in clause

$tagIds = $expense->tags()->pluck('id')->toArray();
$expenseIds = DB::table('expense_tag')->
    whereIn('tag_id',$tagIds)->pluck('expense_id')->toArray();
$relatedexpenses = Expense::whereIn('id', $expenseIds)->get();

note: this uses 3 queries, so it might be slightly slower than a full sql solution, but it should be ok.

Upvotes: 1

Related Questions