as I’m learning symfony2 and doctrine 2 only a few days I have a lot of doubts that may be silly for somebody more experienced.
I have a blog article class with ‘tags’ field:
class Article
{
/**
* @ORM\Column(type="array")
*/
protected $tags;
}
Now, I see Doctrine stores them in DB as ‘longtext’ type in this format:
a:4:{i:0;s:8:"symfony2";i:1;s:3:"php";i:2;s:8:"paradise";i:3;s:7:"symblog";}
Since I made a tag page which shows all articles tagged by selected tag, I need to check if blog article has this tag in its ‘tags array’.
public function getByTag($tag)
{
$likelyBlogs = $this->createQueryBuilder('b')
->select('b')
->where('LOWER(b.tags) LIKE :tag')
->setParameter('tag', '%:"'.$tag.'"%')
->getQuery()
->getResult();
return $likelyBlogs;
}
This works perfectly, however, ->where(‘LOWER(b.tags) LIKE :tag’) looks kinda hacky to me so I want to check if there is any other more ‘natural’ way to check if value exists in an array?
Take a look at many-to-many relations: http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-unidirectional
If you really want to store your tags in the same row as your blog post you should consider using a NoSQL database like MongoDB. But in normal SQL it will be better to normalize your tables and put the tags in a single table.