我正在嘗試創建腳本,該腳本將圖像中的關鍵字導入到數據庫。關鍵字表格中的關鍵字應該是唯一的,但許多圖片可以共享相同的關鍵字。所以我寫了這兩個簡單的模型:Doctrine 2重複檢測
IMAGE:
class Image
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
private $id;
/** @ORM\Column(unique=true, nullable=false) */
private $filename;
/**
* @ORM\ManyToMany(targetEntity="Keyword", inversedBy="images", cascade={"persist"})
* @ORM\JoinTable(name="image_keyword_binder")
*/
private $keywords;
public function __construct()
{
$this->keywords = new \Doctrine\Common\Collections\ArrayCollection();
}
}
KEYWORD:現在
class Keyword
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\Column(type="string", nullable=false, unique=true)
*/
private $text;
/**
* @ORM\ManyToMany(targetEntity="Image", mappedBy="keywords")
*/
private $images;
public function __construct()
{
$this->images = new \Doctrine\Common\Collections\ArrayCollection();
}
}
,導入過程中,對於每一個圖像我想要添加到數據庫只新的關鍵字,如果圖像與現有的關鍵字描述我想添加引用這個現有的。我想實現這樣的代碼:
$images[] = array('filename'=>'image1.jpg', 'keywords'=>array('blue', 'green', 'yellow'));
$images[] = array('filename'=>'image2.jpg', 'keywords'=>array('pink', 'green', 'yellow'));
$images[] = array('filename'=>'image2.jpg', 'keywords'=>array('black', 'green', 'red'));
foreach($images as $img)
{
$image = new \FL\Entity\Image();
$image->setFilename($image['filename']);
$image->setKeywords($image['keywords']);
// em is Entity Manager Instance
$em->persist($image);
$em->flush();
}
另一件要知道的是,我不想在每個循環中都做一次沖洗。我將使用如下所述的東西:http://readthedocs.org/docs/doctrine-orm/en/latest/reference/batch-processing.html批量插入部分。
這都可能嗎? Doctrine可以確定是否存在特定的關鍵字並自動添加參考嗎?在每個循環中從數據庫加載所有現有的關鍵字,並將它們與從圖像加載的新的關鍵字進行比較不是解決方案
到目前爲止,我正在以您描述的方式導入照片。我問了一個問題,因爲我正在尋找更優化的方式。但是知道,目前我做不到的事情也是重要的信息。謝謝。 – qchar 2012-03-01 15:37:46