使用cakephp的find方法来处理这个复杂的SQL

时间:2012-04-21 17:31:36

标签: sql cakephp orm model

我想使用CakePHP的find方法,所以我可以利用它的模型关联。问题是我有这个复杂的SQL搜索,我不知道如何将其翻译成CakePHP的find方法。我刚刚使用$ model-> query()然后在ID上使用Set :: extract。问题是我失去了相关性顺序。如何将其转换为Cake中的find方法以便我可以使用关联?

SQL:

SELECT id, title, SUM(relevance) as total_relevance FROM (
    SELECT 
        card_definitions.id, 
            card_definitions.title,
        (MATCH(card_definitions.title) AGAINST ('%s')) * 5 AS relevance
        FROM card_definitions
    UNION
    SELECT 
        card_definitions.id,
            card_definitions.title,
        (MATCH(card_def_identities.special_ability_text) AGAINST ('%s')) * 0.5 AS relevance
        FROM card_def_identities 
        INNER JOIN card_definitions ON card_def_identities.card_def_sid = card_definitions.id 
    UNION
    SELECT 
        card_definitions.id,
            card_definitions.title,
        (MATCH(brigades.brigade_color) AGAINST ('%s')) AS relevance
        FROM brigades 
        INNER JOIN card_def_brigades ON brigades.id = card_def_brigades.brigade_sid
        INNER JOIN card_definitions ON card_def_brigades.card_def_sid = card_definitions.id 
    UNION
    SELECT 
        card_definitions.id,
            card_definitions.title,
        (MATCH(identifiers.identifier) AGAINST ('%s')) AS relevance
        FROM identifiers
        INNER JOIN card_def_identifiers ON identifiers.id = card_def_identifiers.identifier_sid
        INNER JOIN card_definitions on card_def_identifiers.card_def_sid = card_definitions.id 
    UNION
    SELECT 
        card_definitions.id,
            card_definitions.title,
        (MATCH(card_effects.effect) AGAINST ('%s')) AS relevance
        FROM card_effects
        INNER JOIN card_def_effects ON card_effects.id = card_def_effects.effect_sid
        INNER JOIN card_definitions on card_def_effects.card_def_sid = card_definitions.id 
    ) AS combined_search 
GROUP BY id
HAVING total_relevance > 0
ORDER BY total_relevance DESC
LIMIT 10;

%s被搜索查询取代。

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

两件事:

首先,CakePHP不支持UNION直接从...烤箱。如果你想以一种蛋糕的方式重新创建它,而不是将其转储到query()中,你应该看看Chucks解决方案,他手动创建子查询:UNION syntax in CakePHP。虽然这是为Cake 1.2编写的,但它应该指向正确的方向。子查询的当前文档可以在这里找到:book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries

其次,在开始将这个查询发送到Cake中的任务之前,因为看起来这个查询被反复使用而没有修改(它只是一个搜索对吗?)你可能会发现使用存储过程这是一个很好的情况在您的数据库中。创建过程后,您只需在模型中创建一个直接调用它的方法。下面是MySQL文档所说的内容:Using Stored Routines (Procedures and Functions) 但是使用Adminer(adminer.org)或phpMyAdmin等工具的过程更加微不足道。

(抱歉网址粘贴 - 我只限于两个实际链接!)