php - Cakephp加入查询属于

标签 php mysql cakephp

你好,我的数据库中有三个表。 国家/地区城市。在州表中有一个country_id作为外键,在城市表中有一个state_id作为外键。问题是我想在城市表中查询时获取国家/地区名称。我将分享代码以便您能够充分理解

Country.php

class Country extends AppModel{


    public $useTable = 'countries';
 }

State.php

class City extends AppModel{


    public $useTable = 'cities';

    public $belongsTo = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'state_id',
            'fields' => array('state.id','state.name')

        )
    );

  }

城市

class State extends AppModel{


    public $useTable = 'states';

    public $belongsTo = array(
        'Country' => array(
            'className' => 'Country',
            'foreignKey' => 'country_id',
            'fields' => array('Country.id','Country.name','Country.short_name')

        )
    );

好的,这是代码。如果我使用这个查询

$this->State->find('all', array(
            'conditions' => array(
                'state.country_id' => $country_id
            ),

我可以从国家/地区表中获取国家/地区名称。如果我在城市表中这样做,情况也是如此

$this->City->find('all', array(
                'conditions' => array(
                    'city.state_id' => $state_id
                ),

我可以在这里获取所有州名城市名称。那么现在在同一个表中的一个查询中我如何才能获取国家/地区名称?

最佳答案

尝试使用递归属性。

设置 $this->City->recursive = 2 获取表的关联数据以及关联表上的关联数据。

$this->City->recursive = 2;
$this->City->find('all', array(
            'conditions' => array(
                'city.state_id' => $state_id
            ),
            //other stuff you use in this find
));

您还可以使用“joins”标志。

$this->City->find('all', array(
    'conditions' => array(
        'City.state_id' => $state_id
    ),
    'joins' => array(
        array(
            'table' => 'states',
            'alias' => 'State',
            'type' => 'left',
            'conditions' => 'State.id = City.state_id'
        ),
        array(
            'table' => 'countries',
            'alias' => 'Country',
            'type' => 'left',
            'conditions' => 'Country.id = State.country_id'
        )
    ),
    'fields' => array('City.id', 'State.name', 'Country.name', 
         //include all the fields you need
    )
));

参见:http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive

关于php - Cakephp加入查询属于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35558901/

相关文章:

php - mysqli_affected_rows() 返回 -1 但查询有效

javascript - 仪表板中的 WordPress 小部件卡住

mysql - MySQL OLAP 多维数据集中的外部化时间维度?

php - 从 CakePHP 中的布局文件访问模型

cakephp - cakephp 中的 anchor 标记

cakephp - cakephp 上的供应商和应用程序/供应商之间的区别

php - 实现网页与android的聊天

java - android 网络服务 mysql

c# - 在 C# 中创建数据对象来保存表中的值

php - 在 Laravel 中执行准备好的原始 SQL