0

我的模型中有以下情况:

-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个用户,并且关系是在模型文件中设置的。

我想创建一个操作/视图,允许登录用户只看到他自己的促销,但我不确定如何。

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

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

有小费吗?

谢谢!

4

2 回答 2

0

嗯,你的模型结构有点奇怪。现在看起来每个商店只属于一个用户,每个促销只属于一个商店。如果这是正确的,请确保您的模型关联是正确的。您在这里从用户那里找到它们,因此 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'))));
于 2013-08-02T23:01:30.770 回答
0

在 PromosController 中:

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

在 UsersController 中获取有关用户、他的商店和促销的信息):

$this->User->find('first', array('conditions'=>array(
    'User.id' => $this->Session->read('id'),
    'Store.enabled' => 1),
  'contain'=>array('Store'=>'Promo')
));
于 2013-08-03T00:28:50.593 回答