开发者

CakePHP tables join help

开发者 https://www.devze.com 2023-01-12 07:30 出处:网络
new to cakePHP and trying my first join. I\'ve got one table called users and one called projects. one user can have many projects, so projects has a user_id column.

new to cakePHP and trying my first join. I've got one table called users and one called projects. one user can have many projects, so projects has a user_id column.

Here is my action in 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:

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消