Reputation:
I'm developing a site with Laravel 4.2. I have two tables: articles and tags.
This is my tags table:
id | article_ids | xxxx
2 | 2,41,23,6 | xxxx
I'm using Eloquent and I want to find an specific id in article_ids column. How can I do this?
Can I search in MySQL like this?
Thanks for helping. Sorry for my bad English.
Upvotes: 0
Views: 2680
Reputation: 81127
Pretty much everything has been already said - bad design and you should avoid it and so on and so forth. That's true, I agree.
Do it the right way. However, here's how it's done in MySQL:
// say you want tags related to articles 2 and 23
SELECT * FROM tags
WHERE FIND_IN_SET('2', article_ids)
AND FIND_IN_SET('23', article_ids);
// Eloquent
Tag::whereRaw(
'find_in_set(?, article_ids) and find_in_set(?, article_ids)',
[$id1, $id2] // bindings array
)->get();
Upvotes: 2
Reputation: 179994
This is a very bad way of associating tags with articles, as you've just discovered, because it cannot be easily queried against. Instead, for a many-to-many relationship between the two, you'll want an intermediate table with columns article_id
and tag_id
. For an article with four tags, there'd be four records, one for each association.
Upvotes: 0