如何与Magento进行SQL查询
-
16-10-2019 - |
题
这是AW博客模块的一部分。我有2张桌子。
aw_blog
post_id | tags
1 tag1
2 tag2
3 tag3
aw_blog_post_cat
cat_id | post_id
1 1
1 3
2 3
我有SQL语句,我正在尝试以Magento的方式进行操作:
SELECT `aw_blog`.`tags` FROM `aw_blog_post_cat` RIGHT JOIN `aw_blog` on `aw_blog`.`post_id`=`aw_blog_post_cat`.`post_id` WHERE `aw_blog_post_cat`.`cat_id`=1
我尝试了这样的事情:
$collection = Mage::getModel('blog/blog')->getCollection()
->getSelect()->joinRight(array("post_cat" => $this->getTable('aw_blog_post_cat')), 'main_table.post_id = post_cat.post_id', array());
因此 关联但是没有运气。没有实施的模型 aw_blog_post_cat
桌子
解决方案
我没有测试,因为我没有在Magento安装上安装模块,但是我检查了源代码,我不确定它是否是最新的。您在博客类的集合中拥有AW_BLOG_MODEL_MYSQL4_BLOG_COLLECTY一种方法,该方法有助于基于类别ID过滤内容
class AW_Blog_Model_Mysql4_Blog_Collection
...
public function addCatFilter($catId)
{
$this->getSelect()->join(
array('cat_table' => $this->getTable('post_cat')),
'main_table.post_id = cat_table.post_id',
array()
)
->where('cat_table.cat_id = ?', $catId);
return $this;
}
然后,您可以在代码中使用:
$collection = Mage::getModel('blog/blog')->getCollection()
->addCatFilter(1);
$items = $collection->getItems();
因此,现在您会收到所有帖子项目。
其他提示
Fishpig博客有一篇很棒的文章 编写自定义查询。它详细说明了如何获取查询资源和tabernams。
在您的情况下,这就是这样
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('core_read');
$results = $read->fetchAll("SELECT * FROM {$resource->getTableName('blog/post_cat')}"); // change the query to your needs
var_dump($results);