4

我正在使用 CakePHP 1.3 版本使用搜索插件来实现搜索功能。

我有三个模型:

  • 演示,
  • 国家
  • 状态

Demo有两个外键,country_id并且state_id. State有外键country_id

我正在做的是,我有搜索表单,其中包含国家和州下拉列表,可以从国家和州表中获取所有数据。当我从下拉列表中搜索任何国家并提交表单时,它会显示以下错误。如果我只使用状态下拉列表进行搜索,我会得到正确的结果。

当我执行搜索查询时,我得到了错误

'列' country_id'在where子句中不明确'

我的查询是:

SELECT `Demo`.`id`, `Demo`.`demo2`, `Demo`.`desc`, `Demo`.`subject`, `Demo`.`gender`, `Demo`.`country_id`, `Demo`.`state_id`, `Demo`.`image_url`, `Country`.`id`, `Country`.`name`, `State`.`id`, `State`.`country_id`, `State`.`description` FROM `demos` AS `Demo` LEFT JOIN `countries` AS `Country` ON (`Demo`.`country_id` = `Country`.`id`) LEFT JOIN `states` AS `State` ON (`Demo`.`state_id` = `State`.`id`) WHERE `country_id` = 2

Demo表中的模型关系:

var $belongsTo = array(
    'Country' => array(
        'className' => 'Country',
        'foreignKey' => 'country_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),

    'State' => array(
        'className' => 'State',
        'foreignKey' => 'state_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
);

获取下拉列表中所有国家/地区的控制器查询是:

$country=$this->Country->find('list'); //只在下拉列表中显示国家列表

该查询从除Country( country_id) 之外的所有字段中搜索数据,因为它不知道country_id要从 tableDemo或 table中查找哪个State。我需要country_id从演示表中获得正确的结果。

4

2 回答 2

2

据我了解,您想通过 Demo 查找特定的country_id. 好吧,您应该定义您正在使用的“country_id”,因为这些表中不止一个具有这样的列。

只需使用Demo. country_id在条件数组中:

array('conditions' => array('Demo.country_id' => 2));

您应该会看到 Cake 生成的一些 SQL,如下所示:

SELECT `Demo`.`id`, `Demo`.`demo2`, `Demo`.`desc`, `Demo`.`subject`, `Demo`.`gender`, `Demo`.`country_id`, `Demo`.`state_id`, `Demo`.`image_url`, `Country`.`id`, `Country`.`name`, `State`.`id`, `State`.`country_id`, `State`.`description` FROM `demos` AS `Demo` LEFT JOIN `countries` AS `Country` ON (`Demo`.`country_id` = `Country`.`id`) LEFT JOIN `states` AS `State` ON (`Demo`.`state_id` = `State`.`id`) WHERE `Demo`.`country_id` = 2
于 2012-06-17T07:39:15.577 回答
0

尝试这个:

SELECT
Demo.id,
Demo.demo2,
Demo.desc,
Demo.subject,
Demo.gender,
Demo.country_id,
Demo.state_id,
Demo.image_url,
Country.id,
Country.name,
State.id,
State.country_id,
State.description

FROM demos AS Demo
LEFT JOIN countries AS Country ON (Demo.country_id = Country.id)
LEFT JOIN states AS State ON (Demo.state_id = State.id) WHERE Demo.country_id = 2
于 2012-06-15T12:53:23.197 回答