@Cerad給你一個完全有效的註釋。存儲數組的問題之一是你沒有任何搜索機會。
請參閱PHP/MySQL - Storing array in database和Storing arrays in the database。正如你所看到的那樣,這是一種可怕的做法。
最好的方法是簡單地創建一個類別實體,並與該類別建立OneToMany關係。
這裏是實體書的一個例子,有許多類:
創建類的實體:
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;
}
}
你的書的實體:
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;
}
您現在可以正確搜索。
沒有。您無法查詢數組值。如果你檢查你的數據庫,你會發現它實際存儲爲一個字符串。數組類型是持久化數組的一個原則擴展。數據庫本身並不知道它們。如果你想做這種查詢,那麼你需要用它自己的表來創建一個名爲Category的實體,並將它與主實體相關聯。 – Cerad