Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 2 years ago.
0

You might be able to do it with the whereHas / whereDoesntHave method but in the end they're basically doing the same you do just a lot more complicated. See the official Laravel documentation about querying relations. (Assuming you've got an inverse relationship posts on your Tag model)

Using the whereNotIn on the ids method is fine imho. You could of course use a join instead of 2 queries but there's no Laravel method that does that for you in one statement and without building the needed SQL statement on your own.

The only thing you could do to improve your method is not using the pluck method directly but the getRelatedIds on the relationship.

 $tagIds = $this->tags()->getRelatedIds();
Last updated 8 years ago.
0

Hi @HolgerW1, at first thanks for your answer :-) Please can you give me an example when you say "You could of course use a join instead of 2 queries"? At the moment I can't see another way to achieve the same result... And thanks for the getRelatedIds() method, I didn't knew it and I'm going to look in the Laravels docs

0

ivanhalen said:

Hi @HolgerW1, at first thanks for your answer :-)

You're welcome :-)

Please can you give me an example when you say "You could of course use a join instead of 2 queries"? At the moment I can't see another way to achieve the same result...

SQL joins 101 ;-)

SELECT tags.*
FROM tags
LEFT JOIN taggables
ON tags.id = taggables.tag_id AND taggables.taggable_id=1
WHERE taggables.taggable_id IS NULL

Didn't really test it but should be correct and return all tags that are not connected to the post with ID "1".

The rest should be a piece of cake. You can use the Eloquent query builder to build the needed statement. You shouldn't expect the statement to be any faster than your current implementation though.

Last updated 8 years ago.
0

Uh, I only have to add the taggable_type to the query but that's right! Thank you :-)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

ivanhalen ivanhalen Joined 8 Jul 2014

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.