【问题标题】:CakePHP Associations - hasMany but need to match column in 3rd table?CakePHP 关联 - hasMany 但需要匹配第三张表中的列?
【发布时间】:2015-03-15 00:36:33
【问题描述】:

我是 CakePHP (2.x) 的新手,正在创建一个 post 和 cmets 功能。一切正常,除了我无法弄清楚如何从注册(第三个)表(与“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')));

我已经尝试加入并为文章和 cmets 数组传递两个单独的变量,但随后我必须删除我的关联,这让我相信这不是正确的编码。

表格是:

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!

【问题讨论】:

    标签: php cakephp associations


    【解决方案1】:

    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 插件很棒。

    这是一个示例项目的link,您可以使用 git 进行克隆。

    【讨论】:

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