我是CakePHP(2.x)的新手,正在创建帖子和评论功能。一切正常,除了我无法弄清楚如何从注册(第三)表中获取用户的用户名(与" registration_id"链接)。我的协会目前看起来像:
class Article extends AppModel {
public $hasMany = array('ArticleComment');
public $belongsTo = array(
'ArticleRegistration' => array(
'className' => 'Registration',
'foreignKey' => 'Article.registration_id' //(doesn't work)
),
'ArticleCommentRegistration' => array(
'className' => 'Registration',
'foreignKey' => 'ArticleComment.registration_id' //(doesn't work)
)
);
class ArticleComment extends AppModel {
public $belongsTo = array('Registration','Article');
我不确定ArticleComment中的关联是否正在应用,因为它是通过Article模型调用的。我正在通过以下方式检索数据:
$this->set('articles', $this->Article->find('all', array('order' => 'Article.created desc', 'limit' => '3')));
我尝试过连接并为文章和注释数组传递两个单独的变量,但后来我必须删除我的关联,这使我相信它不是正确的编码。
表格是:
articles
__________
id
registration_id
body
article_comments
__________
id
article_id
registration_id
body
registration
__________
id
username
我正在获取信息:
$this->set('articles', $this->Article->find('all', array('order' => 'Article.created desc')));
TIA!
答案 0 :(得分:0)
进行find()
调用时,cakephp生成的SQL查询如下
SELECT `Article`.`id`,
`Article`.`registration_id`,
`Article`.`body`,
`Registration`.`id`,
`Registration`.`username`
FROM `test`.`articles` AS `Article`
LEFT JOIN `test`.`registration` AS `Registration`
ON (`Article`.`registration_id` = `Registration`.`id`)
WHERE 1 = 1 LIMIT 20
因此,为了访问用户名,您只需在视图中编写类似的内容
$articles['Registration']['username'];
我建议你使用cakephp bake命令,我可以在10分钟内完成这个项目。而且我建议使用Netbeans作为IDE,cakephp插件很棒。
以下是您可以使用git克隆的示例项目的link。