使用MySQL Match和Union进行ZEND搜索

时间:2012-11-03 22:28:25

标签: mysql zend-framework search zend-db

我必须承认我无法弄清楚如何完成这个。我可以在MySql中使用查询,我可以在Zend Framework中获得简单的表或视图查询,但这超出了我的范围!

这是我正在尝试运行的查询:

SELECT * from (
SELECT 
'Tab' as 'table_name', TabId as id, `TabTitle` as title,
(MATCH(`TabTitle`,`TabSubTitle`) AGAINST (@target)) as relevance
from Tab
UNION
SELECT 
'Tab2' as 'table_name', 
Tab2Id as id, `Tab2Title` as title,
(MATCH(`Tab2Title`,`Tab2Desc`) AGAINST (@target)) as relevance
from Tab2
)
as sitewide WHERE relevance > 0 order by relevance DESC;

我想提供一些关于如何将其发送到Zend的MVC框架中的指示!

编辑添加:

这是我正在使用的当前模型代码,它给出了一个错误“传递给Zend_Paginator_Adapter_DbTableSelect :: __ construct()的参数1必须是Zend_Db_Select的一个实例,给定字符串,”

class Application_Model_Search extends Zend_Db_Table
{
protected $_name = ‘Search’;
protected $_primary = 'SearchId';

function getSearchResults($page, $searchTerm) 
{

    $query = "
SELECT * from (
 SELECT 
 'Tab' as 'table_name', TabId as id, `TabTitle` as title,
 (MATCH(`TabTitle`,`TabSubTitle`) AGAINST (@target)) as relevance
 from Tab
 UNION
 SELECT 
 'Tab2' as 'table_name', 
 Tab2Id as id, `Tab2Title` as title,
 (MATCH(`Tab2Title`,`Tab2Desc`) AGAINST (@target)) as relevance
 from Tab2
)
as sitewide WHERE relevance > 0 order by relevance DESC;        
    ";

    echo ($query);      

    $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($query));
    $paginator->setItemCountPerPage(15); //
    $paginator->setCurrentPageNumber($page); 
    return $paginator; 


}


}

1 个答案:

答案 0 :(得分:1)

    $config = array (
        'dbname' => 'test',
        'password' => 'passwd',
        'username' => 'user'
    );

    $database = new Zend_Db_Adapter_Mysqli ($config);

    $query_1 = new Zend_Db_Select ($database);
    $query_1->from ('Tab', array (
        'Tab AS table_name',
        'TabId AS id',
        'TabTitle` as title',
        new Zend_Db_Expr ('(MATCH(`TabTitle`,`TabSubTitle`) AGAINST (@target)) as relevance')
    ));

    $query_2 = new Zend_Db_Select ($database);
    $query_2->from ('Tab2', array (
        'Tab2 AS table_name',
        'Tab2Id AS id',
        'Tab2Title` as title',
        new Zend_Db_Expr ('(MATCH(`Tab2Title`,`TabDesc`) AGAINST (@target)) as relevance')
    ));

    $query = $database->select ()
        ->union (array (
        $query_1,
        $query_2
    ));

    echo $database->select ()->from ($query)->where ('relevance>0')
        ->order ('relevance DESC');