【发布时间】:2015-03-17 14:52:03
【问题描述】:
我遇到了以下问题:我想在不破坏 Symfony 应用程序默认行为的情况下获取特定语言环境的学说实体。
这是我的一个实体的示例:
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Entity(repositoryClass="ProductRepository")
* @ORM\Table(name="product")
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
*/
class Product
{
/**
* @var integer $id
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(name="name", type="string")
* @Gedmo\Translatable
*/
protected $name;
// ...
}
相关学说库的一部分:
class ProductRepository extends \Doctrine\ORM\EntityRepository
{
public function findOneProductInLocale($id, $locale)
{
$qb = $this->createQueryBuilder('p')
->select('p')
->where('p.id = :id')
->setMaxResults(1)
->setParameter('id', $id);
;
$query = $qb->getQuery();
$query->setHint(
\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
);
// force Gedmo Translatable to not use current locale
$query->setHint(
\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
$locale
);
$query->setHint(
\Gedmo\Translatable\TranslatableListener::HINT_FALLBACK,
1
);
return $query->getOneOrNullResult();
}
}
以及我的部分脚本:
// default Locale: en
// request Locale: de
$repo = $em->getRepository('Acme\\Entity\\Product');
$product1 = $repo->findOneById($id);
echo $product1->getName(); // return 'Name (DE)'
$product_de = $repo->findOneProductInLocale($id, 'de');
echo $product_de->getName(); // return 'Name (DE)';
$product_en = $repo->findOneProductInLocale($id, 'en');
echo $product_en->getName(); // return 'Name (EN)'
echo $product1->getName(); // return 'Name (EN)' instead of 'Name (DE)' !! <-- What is wrong?
// even if I refetch a product
$product2 = $repo->findOneById($id);
echo $product2->getName(); // return 'Name (EN)' without taking anymore in account the current locale
现在有人为什么这没有按预期工作?
我的ProductRepository::findOneProductInLocale() 的实现有问题吗?
欢迎任何帮助或提示。
【问题讨论】:
-
因为您已经在 Product Repository 中设置了后备!
$query->setHint( \Gedmo\Translatable\TranslatableListener::HINT_FALLBACK, 1 );这里 1 表示回退到默认语言环境
标签: php symfony doctrine-orm doctrine translate