如何在Magento集合中添加字段选择查询作为字段

如何在Magento集合中添加字段选择查询作为字段,magento,Magento,我有一个名为mymodule/class的Magento集合。我的Magento db中有两个表class和student 类别表: id clas_name 学生表: id class_id student_name 学生表中的class\u id是class表中id的外键 我想创建mymodule/class集合,以便sql如下所示: select a.*, (select count(id) FROM studetn WHERE cl

我有一个名为
mymodule/class
的Magento集合。我的Magento db中有两个表
class
student

类别表:

id     clas_name
学生表:

id   class_id    student_name
学生表中的
class\u id
是class表中
id
的外键

我想创建
mymodule/class
集合,以便sql如下所示:

select a.*, (select count(id) FROM studetn 
                WHERE class_id = a.id) as student_count 
FROM class a
或者,我想从上面的sql中创建
mymodule/class


如何做任何建议?

首先创建模块控制文件模块名称

 Amit_Custommodule.xml at app/etc/modules/ 
代码

<?xml version="1.0"?>
<config>
    <modules>
        <Amit_Custommodule>
            <codePool>community</codePool>
            <active>true</active>
        </Amit_Custommodule>
    </modules>
</config>
如果我们定义模型,那么我们需要定义模型Custommodule.php的资源类

资源类我的模块是Custommodule.php
app/code/community/Amit/Custommodule/Model/Resource
/和code

<?php
class Amit_Custommodule_Model_Resource_Custommodule extends Mage_Core_Model_Resource_Db_Abstract
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('custommodule/custommodule', 'id');
    }
    public function getMyCount($std)
{
    $Table = Mage::getSingleton('core/resource')->getTableName('custommodule/custommodule');

    $select = $this->getReadConnection()->select()
        ->from(
            array('main_table' => $Table),
            array(new Zend_Db_Expr('COUNT(main_table.id)'))
        )
        ->where('main_table.id = :id');

    $bind = array('id' => (int)$std->getId());
    $counts = $this->getReadConnection()->fetchOne($select, $bind);

    return intval($counts);
}

}

更多细节
看起来您必须在查询中添加列。在您已经拥有collection的场景中,让我们假设您的$collection变量如下:

$collection = Mage::getModel("mymodule/class")->getCollection()
因此,您必须修改查询,如下所示:

$collection->getSelect()->columns(
        array(
            'student_count' => new Zend_Db_Expr('(SELECT count(id) FROM student WHERE class_id=main_table.id)'
        )));

上面的表达式将生成您编写的查询。

感谢Amit的精彩解释。这是一篇了不起的文章。但这并不是我正在寻找的答案。@krishna密码是工作物品…你的问题也很好。我两个都给了我想要的东西。
<?php
class Amit_Custommodule_Model_Resource_Custommodule_Collection
extends Mage_Core_Model_Resource_Db_Collection_Abstract{
    protected function _constuct(){
        $this->_init('custommodule/custommodule');    
    }
}
$Collection=Mage::getModel("custommodule/custommodule")->Collection(); 

foreach($Collectio as $each)
{
$each->getMyCount();
}
$collection = Mage::getModel("mymodule/class")->getCollection()
$collection->getSelect()->columns(
        array(
            'student_count' => new Zend_Db_Expr('(SELECT count(id) FROM student WHERE class_id=main_table.id)'
        )));