mysql - CakePHP-SQL : joining tables

标签 mysql cakephp join

我有 4 张 table :

stores {id, name, owner_id, city_id, ...}
store_managers {id, store_id, user_id, ...}   // since I'm not associating (i have my reasons) the table to the others by cake's association, the name is not by the cakePHP naming conventions. 
cities {id, name, ...}
users {id, name, ...}

现在..在stores_controller中有一个名为“stores_stats()”的函数,它收集有关用户拥有的商店的一些统计信息并显示它。 Owner_id 来自 $this->Auth->user('id')
我想使用 $this->Store->find('all') 调用来获取以下信息:

  1. 商店记录本身。
  2. 各商店的商店经理。
  3. 每家商店的城市记录。
  4. 商店记录本身。

userscities 表与 stores 表和 find('all') 查询正确返回有关它们的数据。我的问题是 store_managers 表。

如何将store_managers加入到查询中? 而且,只是为了正确 - 我自己如何编写这样的查询? 以下查询给了我一些东西..其他..

SELECT *
FROM stores
LEFT JOIN cities ON stores.id = cities.id
LEFT JOIN store_managers ON store_managers.store_id = stores.id
WHERE stores.id = 122 AND stores.owner_id = 3

最佳答案

您可能想要使用 CakePHP 的可容纳行为。 (read more about it here)。

//Store Model
class Store extends AppModel {

var $actsAs = array('Containable');

//associations
//validation

//the method you call from the controller
function getStoreStats() {
    $this->recursive = -1;
    $params = array();
    $params['containable'] = array(
        'User' => array(
             'StoreManager',
        ),
        'City'
    );
    $data = $this->find('all', $params);
    return $data;
}
}

这个想法是,您将 recursive 设置为 -1,这会将您从 Store 返回的数据限制为自身。然后,使用 containsable 指定要返回的其他相关数据。

确保您正在阅读 CakePHP 书籍,以验证您使用的是正确的版本(1.3、2.0...等)。

此外,在应用模型中设置 $this->recursive=-1; 是很常见的,它是所有应用程序的默认设置。

假设您的所有关系都已正确设置,并且没有一个是 HABTM 关系,则 Containable 应该非常适合您。

关于mysql - CakePHP-SQL : joining tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8728947/

相关文章:

php - 合并 2 个数组并对值求和(数字键)

CakePHP 方法可见性

MySQL 连接表返回多行作为一个结果,SUM() 是否已解决?

join - 在include in sequelize(node.js express)中使用models.sequelize.col()时出现模棱两可的错误

mysql - 无法使用仅主机网络连接到在 Virtualbox ubuntu 虚拟机上运行的 mysql 数据库

php - 将列表框选项值保存到 mysql 中,然后再次显示 php mysql

IN 子句中的 MySQL 多列

CakePHP 自定义全局函数

authentication - cakephp 基于组的权限

c# - 组合多个列表