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();
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
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.
Uh, I only have to add the taggable_type to the query but that's right! Thank you :-)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community