@Cerad给了你一个完全有效的评论。存储数组的问题之一是您没有任何搜索机会。
请参阅PHP/MySQL - 在数据库中存储数组和在数据库中存储数组。如您所见,这是一种可怕的做法。
最好的方法是简单地创建一个 Category 实体,并与该类别建立 OneToMany 关系。
下面是一个实体 Book 的例子,它有很多类别:
1 创建您的类别实体:
class Category implements CategoryInterface
{
//.....
/**
* Title of the category
*
* @ORM\Column(type="string", length=100)
*/
protected $title;
/**
* Relation with your book entity for example
*
* @ORM\ManyToOne(targetEntity="Book", inversedBy="categories")
* @ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
private $book;
/**
* Set book
*
* @param BookInterface $book
*/
public function setBook(BookInterface $book)
{
$this->book = $book;
}
/**
* Get book
*
* @return BookInterface
*/
public function getBook()
{
return $this->book;
}
}
2 您的图书实体:
use Doctrine\Common\Collections\ArrayCollection;
class Book implements BookInterface
{
/**
* Categories for the books
*
* @ORM\OneToMany(targetEntity="Category", mappedBy="book")
* @var CategoryInterface[]
*/
protected $categories ;
public function __construct()
{
$this->categories = new ArrayCollection();
}
/**
* Add Categories
*
* @param CategoryInterface $category
*/
public function addCategory(CategoryInterface $category)
{
$category->setBook($this);
$this->categories->add($category);
}
/**
* Remove Category
*
* @param CategoryInterface $category
* @return bool
*/
public function removeCategory(CategoryInterface $category)
{
return $this->categories->removeElement($category);
}
/**
* Get Categories
*
* @return Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set Categories
*
* @param ArrayCollection $categories
*/
public function setCategories($categories) {
$this->categories->clear();
foreach ($categories as $category) {
$this->addCategory($category);
}
return $this;
}
3 您现在可以正确搜索。