简体   繁体   English

CakePHP表加入帮助

[英]CakePHP tables join help

new to cakePHP and trying my first join. CakePHP的新手,并尝试我的第一次加入。 I've got one table called users and one called projects. 我有一张桌子叫用户,一张桌子叫项目。 one user can have many projects, so projects has a user_id column. 一个用户可以有多个项目,因此项目具有一个user_id列。

Here is my action in projects_controller: 这是我在projects_controller中的操作:

function index() {

    $this->set('projects', $this->Project->find('all', array('joins' => array(
        array(
            'table' => 'users',
            'alias' => 'UsersTable',
            'type' => 'inner',
            'foreginKey' => false,
            'conditions' => array('UsersTable.id = Project.user_id')
        )
    ))));




}

Here is the SQL dump: 这是SQL转储:

SELECT `Project`.`id`, `Project`.`title`, `Project`.`created`, `Project`.`website`, `Project`.`language_id`, `Project`.`user_id` FROM `projects` AS `Project` inner JOIN users AS `UsersTable` ON (`UsersTable`.`id` = `Project`.`user_id`) WHERE 1 = 1

As you will see everything seems fine except its not selecting anything from the users table but it is joining it. 如您所见,除了它没有从用户表中选择任何东西,而是将其连接之外,其他一切看起来都不错。

And here is my view: 这是我的看法:

<table>
<tr>
    <th>Name</th>
    <th>User</th>
</tr>



<?php foreach ($projects as $project): ?>
<tr>
    <td>
        <?php echo $html->link($project['Project']['title'], array('controller' => 'projects', 'action' => 'view', $project['Project']['id'])); ?>
    </td>   
    <td>
        <?php echo $html->link($project['Project']['username'], array('controller' => 'users', 'action' => 'view', $project['Project']['user_id'])); ?>
    </td>   
</tr>
<?php endforeach; ?>

Have I messed up somewhere? 我在某个地方搞砸了吗? the view attempts to list all projects along with the user who owns it. 该视图尝试列出所有项目以及拥有它的用户。

Thanks alot, 非常感谢,

Jonesy 琼斯

Found out that what I wanted to be achieved by editing the projects model to: 发现我想要通过将项目模型编辑为以下内容来实现:

var $belongsTo = array(
    'User' => array(
        'className'    => 'User',
        'foreignKey'    => 'user_id'
    )
); 

This did the trick! 这成功了!

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

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