简体   繁体   English

在cakephp中基于另一个表获取一个表的条目

[英]Get entries of one table based on another table in cakephp

I have two tables , 我有两个桌子,

moods and votes, 心情和投票,

votes contains votes for each mood added using parameter vote.moodId 投票包含使用参数vote.moodId添加的每种心情的投票

I am trying to get specific types of moods added on which i have voted. 我正在尝试添加已投票的特定类型的情绪。 I am using cake php 我正在使用蛋糕php

$conditions = array(
                'Mood.userId'=>$userId,
                                'Mood.moodType'=>MOOD_IT
                );

            $moods = $this->Mood->find('all', array('conditions'=>$conditions,
            'fields' => $this->mood_fields_it,
            'order' => array('Mood.created DESC'),
                        'limit' => 20,
                        'offset' => $offset * 20
            ));

For now this is getting all moods added in database using my userId, instead how can i get the moods on which i have voted not that have userId = myUserid? 现在,这是使用我的userId将所有情绪添加到数据库中,而不是如何获得我没有投票通过的userId = myUserid的情绪?

Your Mood.php model should have 您的Mood.php模型应该具有

public $hasMany = array(
    'Vote' => array(
        'className' => 'Vote',
        'foreignKey' => 'mood_id'
    )
);

In your votes table make sure you add a column mood_id (integer). 确保在投票表中添加一列mood_id (整数)。 This binds the Votes to the Moods. 这将投票绑定到情绪上。 To filter based on related models you can use Containable. 要基于相关模型进行过滤,可以使用Containable。 Add the following to your AppModel.php: 将以下内容添加到您的AppModel.php中:

public $actsAs = array('Containable');

Then your find should look like this: 然后您的发现应如下所示:

$conditions = array(
                'Mood.userId !='=>$userId, // all Moods that not yours
                 'Mood.moodType'=>MOOD_IT
              );

$moods = $this->Mood->find('all', 
                            array(
                                'conditions'=>$conditions,
                                'contain' => array('Vote' => array(
                                                              'conditions'  =>  array('Vote.userId' =>  $userId) // find your votes
                                                             )
                                                    ),
                                'fields' => $this->mood_fields_it,
                                'order' => array('Mood.created DESC'),
                                'limit' => 20,
                                'offset' => $offset * 20
                            ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM