我的控制器中有以下代码:
foreach ($image->tags as $tag) {
$existingTag = $em->getRepository('AppMainBundle:InstagramTag')->findOneByTag($tag);
if ($existingTag) {
ladybug_dump('existing tag');
} else {
ladybug_dump('non existing tag');
$instagramTag = new InstagramTag();
$instagramTag->setTag($tag);
$em->persist($instagramTag);
}
}
这是我的实体:
/**
* @ORM\Entity
* @ORM\Table(name="app_instagram_tag")
* @ORM\HasLifecycleCallbacks()
*/
class InstagramTag
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(name="tag", type="string", nullable=true)
*/
private $tag;
/**
*
* @ORM\OneToMany(targetEntity="App\MainBundle\Entity\InstagramPictureTag", mappedBy="tag")
*/
private $picturetag;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get tag
*
* @return string
*/
public function getTag()
{
return $this->tag;
}
/**
* Set tag
*
* @param string $tag
* @return InstagramTag
*/
public function setTag( $tag)
{
$this->tag = $tag;
return $this;
}
}
我最初使用名为app_instagram_tag的空表开始。 $ image->标记是一个字符串数组,例如["abc", "test", "etc"]
。当我开始使用空表时,它怎么可能一直打印existing tag
?
答案 0 :(得分:0)
@adit,理论上$ existingTag应为'NULL'。尝试var_dump($ existingTag)并查看此变量中包含的值。另外,如果我是你,我会将代码更改为:
<?php
...
$repository = $em->getRepository('AppMainBundle:InstagramTag');
foreach ($image->tags as $tag) {
$existingTag = $repository->findOneByTag($tag);
if ($existingTag) {
var_dump($existingTag); // this line is just to find out why your logic is falling in here when should go to the else. Maybe change the logic for if ($existingTag === NULL) {
ladybug_dump('existing tag');
} else {
ladybug_dump('non existing tag');
$instagramTag = new InstagramTag();
$instagramTag->setTag($tag);
$em->persist($instagramTag);
}
}
我希望它有所帮助。
答案 1 :(得分:-1)
尝试使用
if(isset($existingTag)) {
}
而不是
if ($existingTag)