【问题标题】:Joins tables in Cakephp在 Cakephp 中加入表
【发布时间】:2013-02-28 01:09:46
【问题描述】:

我有两个表,即;历史和用户。我需要显示如下数据:


标识 |用户名 |最新创建的帖子 |首次创建帖子

id 和 username 的数据来自 users 表,最后创建和首次创建的 post 数据来自历史记录。我需要查看所有用户,他们最近创建的帖子和他们第一个创建的帖子。请帮我制作控制器并查看谢谢

【问题讨论】:

  • 两个表都通过外键相互关联。?关联在模型中定义。

标签: cakephp


【解决方案1】:

试试下面。

<?php
    $users = $this->User->find('all',array
    (
        'conditions' => array
        (
            //conditions goes here
        ),
        'fields' => array
        (
            'User.id',
            'User.username',
            'History.Lastest created Post',
            'History.First created Post'
        )
    ));
?>

【讨论】:

    【解决方案2】:

    假设 'User' 和 'History' 表之间的关系是一对一的,并且 History 表中有一个 'user_id' 列,您可能需要在 中指定它们之间的关系>历史模型,例如:

       var $hasOne = array(
         'User' => array(
                'className' => 'User',
                'foreignKey' => 'user_id',
                'conditions' => '',
                'fields' => '',
                'order' => ''
           )
        );
    

    然后,您需要执行joins 来执行此操作。例如,在您的 User 模型中的某处,尝试如下操作:

     class User extends AppModel {    
    
            ....  
    
           function getAllUsersHistory{
    
                 $allHistories = $this->find('all', array(
                    'joins' => array(
                        'table' => 'history',
                        'alias' => 'HistoryJoin'
                        'type' => 'INNER',
                        'conditions' => array(
                            // your conditions, for example: 'History.user_id' => 'User.id'
                        )
                    ),  
                    'fields' => array(
                        'User.id', 
                        'User.username', 
                        'History.lastest_created_post', 
                        'History.first_created_post'
                    )           
                 ));   
    
              return $allHistories; 
    
             }
    
             .....
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多