0

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.

2
  • 2
    bad table design, a table with one id per article_id makes much for sense Commented Jan 20, 2015 at 21:24
  • yea, but i want to learn this for another projects. It's important for me. Commented Jan 20, 2015 at 21:29

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

thx for answer, i'll do tags the right way. I just need learn this. Query is true, but how can i do this with laravel.
0

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.

1 Comment

okey, this is so bad for tags. So, there is an another project for me. I'm trying message_groups and messages. i thought save users_id in message_groups's users column. And find who people in the message_group. Do you know best way for this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.