mysql - 教义 DQL 到 QueryBuilder

标签 mysql symfony doctrine-orm dql

也许有人可以帮我改造

我试图通过 page_id 获取与 theFaqPageQuestionContent 无关的 QuestionContent 并在选择框中查看它

SELECT q FROM VswSystemCmsBundle:QuestionContent q WHERE q.id NOT IN
        (SELECT fq.questioncontent_id FROM VswSystemCmsBundle:FaqPageQuestionContent fq WHERE fq.faqcontentpage_id = :page_id) 

进入 QueryBuilder 表单以在 Sf2 表单中使用它。

最佳答案

现在您已经阐明了您想要做什么,我建议您在连接到您的 QuestionContent 实体的表单上使用“实体”字段类型。

// don't forget the use statement for your repository up top
use Your\VswSystemCmsBundle\Repository\QuestionContentRepository;

// in buildForm() (this assumes you have $pageId set properly)
$builder
    ->add('questionContent', 'entity', array(
        'class'         => 'VswSystemCmsBundle:QuestionContent',
        'property'      => 'questionForForm',
        'query_builder' => function(QuestionContentRepository $repo) use ($pageId) { 
            return $repo->findNotAttachedQuestions($pageId);
        },
    ))
;

编辑:将您的 QueryBuilder 放入该实体的存储库并从那里调用它。

// this is Your\VswSystemCmsBundle\Repository\QuestionContentRepository class
public function findNotAttachedQuestions($pageId)
{
    $subQuery = $this->createQuery("
            SELECT  fq.questioncontent_id 
            FROM    VswSystemCmsBundle:FaqPageQuestionContent fq
            WHERE   fq.faqcontentpage_id = :page_id
        ")
        ->setParameter('page_id', $pageId)
    ;

    return $this->createQueryBuilder('q')
        ->where($qb->expr()->notIn('q.id', $subQuery))
    ;
}

请注意我如何将上面的“属性”定义为 questionForForm?我们需要向您的 QuestionContent 实体添加一个 getter 函数,以返回问题的前 30 个字符。

// this is Your\VswSystemCmsBundle\Entity\QuestionContent class
public function getQuestionForForm()
{
    return substr($this->getQuestion(), 0, 30);
}

现在一切都在正确的地方分开了。您不必担心将 DQL 转换为 Doctrine QueryBuilder 实例,因为您在存储库中拥有它并从那里调用它。您不必创建自定义数组来为选择返回数据,而且您现在有一个可重用的函数,它直接从实体返回问题的前 30 个字符。

关于mysql - 教义 DQL 到 QueryBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470233/

相关文章:

php - 在 Symfony 中创建全局函数的最佳方法

rest - 使用复杂实体构建 REST APi

mysql - 当复选框被选中时如何将表单数据插入到mysql?

MySql 使用 CASE 从另一个表中插入子字符串

symfony - Doctrine 中的反向 bool 值

Symfony2 : do not update a form field if not provided

php - 学说 DQL JOIN

php - 使用教义和 PHP 进行库存管理

php - 有没有办法在 php 中使用 $result->fetch_row 显示数据库中的图像?

php - MySQL 不是有效资源