我有 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')
调用来获取以下信息:
- 商店记录本身。
- 各商店的商店经理。
- 每家商店的城市记录。
- 商店记录本身。
users
和 cities
表与 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/