【问题标题】:How can I build this query in doctrine Zend如何在学说 Zend 中构建此查询
【发布时间】:2025-12-19 05:15:06
【问题描述】:

我有所有的模型。我需要在教义中定义关系并使用教义构建查询。

没有教义的查询可以正常工作。

SELECT * FROM asset_site_link l
join assets a on l.assetID = a.id
join assetTypes t on t.id = a.assetTypeID
join assetCategories c on c.id = a.categoryID
where t.name="image" AND c.name = "static_banner"
and l.siteID = "2"

我的第一次尝试是这样的,但没有奏效。

 $q = Doctrine_Query::create()
    ->select('r.*')
    ->from('assetManagement_Model_asset r')
    ->leftJoin('r.assetTypeID t')
    ->leftJoin('r.categoryID c')  
    ->leftJoin('r.assetSiteLink l')                        
    ->where('r.isDeleted = 0')
    ->andWhere('t.name = ?', "image")
    ->andWhere('c.name = ?', "static_banner")
    ->andWhere ('l.siteID = ?', "2");

虽然下面的查询工作正常(没有assetSiteLink 连接)

 $q = Doctrine_Query::create()
    ->select('r.*')
    ->from('assetManagement_Model_asset r')
    ->leftJoin('r.assetTypeID t')
    ->leftJoin('r.categoryID c')  
    ->where('r.isDeleted = 0')
    ->andWhere('t.name = ?', "image")
    ->andWhere('c.name = ?', "static_banner");

只是告诉你 Asset 模型与 AssetSiteLink 是一对多的关系

有什么想法吗?

【问题讨论】:

    标签: zend-framework doctrine


    【解决方案1】:
       $q = Doctrine_Query::create()
            ->select('r.*, l.*')
            ->from('linkManagement_Model_assetSiteLink l')
            ->leftJoin('l.assetSiteLink r')                        
            ->leftJoin('r.assetTypeID t')
            ->leftJoin('r.categoryID c')              
            ->where('r.isDeleted = 0')
            ->andWhere('t.name = ?', "image")
            ->andWhere('c.name = ?', "static_banner")
            ->andWhere('l.siteID = ?', "2")
       ;
    

    【讨论】:

    • 我相信如果您在基类中正确设置关系,则不需要在查询中使用 join 语句。它会自动选择相关记录
    【解决方案2】:

    如果有人想知道为什么上面的代码不会为他们执行,可能是由于使用了“andWhere()”函数。在我的 Zend Framework 版本中,没有“andWhere()”函数;您只需调用 where() 两次即可。

    这意味着,对我来说,上面的代码需要这样写:

    q = Doctrine_Query::create()
            ->select('r.*, l.*')
            ->from('linkManagement_Model_assetSiteLink l')
            ->leftJoin('l.assetSiteLink r')                        
            ->leftJoin('r.assetTypeID t')
            ->leftJoin('r.categoryID c')              
            ->where('r.isDeleted = 0')
            ->where('t.name = ?', "image")
            ->where('c.name = ?', "static_banner")
            ->where('l.siteID = ?', "2")
    

    【讨论】: