mysql - 如何编写 CakePHP 模型查询

标签 mysql cakephp cakephp-2.1

我的模型中有以下情况:

-a "users" table, with "id" as primary key
-a "stores" table with "id" as primary key, and "users_id" as foreign key
-a "promos" table with "id" as primary key, and "stores_id" as foreign key

换句话说,每个促销只属于 1 个商店,每个商店只属于 1 个用户,并且关系是在模型文件中设置的。

我想创建一个操作/ View ,允许登录用户只能看到他自己的促销,但我不知道如何实现。

以下代码向我显示一条错误消息,因为“User.id”不是促销表的一部分,但我不知道如何创建参数来将促销列表限制为仅此用户拥有的商店。

$allPromos = $this->Promo->find('all', array('conditions' => array('Store.id' => $storeId, 'Store.enabled' => 1, 'User.id' => $this->Session->read('id'))));

有什么建议吗?

谢谢!

最佳答案

嗯,你的模型结构有点奇怪。现在看起来每个商店只属于一个用户,每个促销也只属于一个商店。如果这是正确的,请确保您的模型关联是正确的。 您可以从此处的用户处找到它们,因此 User.php 需要 var $hasMany = array('Store') 而 Store.php 需要 var $hasMany = array('Promo')

$allPromos = $this->User->find('all', 
                               array('fields' => array('Promo.*'),
                                     'contain' => array('Store', 'Promo'),
                                     'recursive' => 2 //Two levels of recursion to get from User to Store to Promo
                                     'conditions' => 
                                     array('Store.id' => $storeId, 
                                           'Store.enabled' => 1, 
                                           'User.id' => $this->Session->read('id'))));

关于mysql - 如何编写 CakePHP 模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18027269/

相关文章:

mysql - SQL中如何正确使用左连接

mysql - 是否可以使用 MYSQL GROUP BY 选择堆栈值

php - 为什么此上传文件代码在 CakePHP 中不起作用

php - 如何从 Controller 将 Assets (JS) 包含到布局中 - CakePHP

cakephp - 什么是 CakePHP 行为?

database - CakePHP 2.1 按自定义顺序显示记录

mysql - MySQL中的base64编码

mysql - 在 phpMyAdmin 中导入带有多边形数据的 CSV

php - Cakephp 缓存关联结果

internet-explorer - cakephp 在使用 Safari 和 Internet Explorer 时丢失 session