【问题标题】:Querying across multiple tables in CakePHP 3.x ORM在 CakePHP 3.x ORM 中跨多个表进行查询
【发布时间】:2014-12-10 01:06:17
【问题描述】:

我有三个表Countries、CitiesAddresses。他们的关系是国家有很多城市,城市有很多地址。所以它类似于国家->城市->地址。

如果我想获取某个城市的所有地址,我可以这样做

$this->paginate = [
        'contain' => ['Cities']
    ];
    $this->set('addresses', $this->paginate($this->Addresses));

如果我想获得某个国家/地区的所有城市,我也可以这样做。

我想要的是获取某个国家/地区的所有地址。

注意:地址包含国家/地区的外键,而是在城市中。

可能的查询是:SELECT a.*, c.* FROM countries a LEFT JOIN cities b ON a.id=b.country_id LEFT JOIN addresses c ON b.id=c.city_id

【问题讨论】:

标签: php cakephp


【解决方案1】:

我认为您正在寻找这样的东西 (from the docs):

    <?php

    $query = $countries->find()
        ->hydrate(false)
        ->join([
            'City' => [
                'table' => 'cities',
                'type' => 'LEFT',
                'conditions' => 'Country.id = City.country_id'
            ],
            'Address' => [
                'table' => 'addresses',
                'type' => 'LEFT',
                'conditions' => 'City.id = Address.city_id'
            ]
        ]);

hydratate 方法告诉 ORM 不要尝试生成实体。如果您希望生成实体,请尝试删除该部分。

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多