CakePHP 表连接帮助
cakePHP 新手,正在尝试我的第一次加入。我有一张名为用户的表和一张名为项目的表。一个用户可以有多个项目,因此项目有一个 user_id 列。
这是我在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')
)
))));
}
这是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
如您所见,一切看起来都很好,除了它没有从users 表中选择任何内容,而是加入它。
这是我的观点:
<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; ?>
我是不是哪里搞砸了?该视图尝试列出所有项目以及拥有该项目的用户。
非常感谢,
琼斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发现我想要通过将项目模型编辑为来实现:
这成功了!
Found out that what I wanted to be achieved by editing the projects model to:
This did the trick!