在CakePHP中定义两个模型之间同时具有多个和具有一个关联的方法? [英] Method for defining simultaneous has-many and has-one associations between two models in CakePHP?

查看:94
本文介绍了在CakePHP中定义两个模型之间同时具有多个和具有一个关联的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CakePHP框架中,我一直遇到的问题是定义两个模型之间的同时hasOnehasMany关系.例如:

One thing with which I have long had problems, within the CakePHP framework, is defining simultaneous hasOne and hasMany relationships between two models. For example:

BlogEntry hasMany Comment
BlogEntry hasOne MostRecentComment(其中MostRecentComment是具有最新created字段的Comment)

BlogEntry hasMany Comment
BlogEntry hasOne MostRecentComment (where MostRecentComment is the Comment with the most recent created field)

在BlogEntry模型属性中定义这些关系是有问题的. CakePHP的ORM作为INNER JOIN实现一个一对一的关系,因此,一旦有多个注释,BlogEntry::find('all')调用将为每个BlogEntry返回多个结果.

Defining these relationships in the BlogEntry model properties is problematic. CakePHP's ORM implements a has-one relationship as an INNER JOIN, so as soon as there is more than one Comment, BlogEntry::find('all') calls return multiple results per BlogEntry.

过去,我通过以下几种方法来解决这些情况:

I've worked around these situations in the past in a few ways:

  1. 使用模型回调(或者有时甚至在控制器或视图中!),我使用以下命令模拟了MostRecentComment:
    $this->data['MostRecentComment'] = $this->data['Comment'][0];
    如果说我需要用Comment.created以外的任何其他方式订购评论",这将变得非常丑陋.它还没有Cake的内置分页功能,无法按MostRecentComment字段进行排序(例如,按MostRecentComment.created反向按时间顺序对BlogEntry结果进行排序.

  1. Using a model callback (or, sometimes, even in the controller or view!), I've simulated a MostRecentComment with:
    $this->data['MostRecentComment'] = $this->data['Comment'][0];
    This gets ugly fast if, say, I need to order the Comments any way other than by Comment.created. It also doesn't Cake's in-built pagination features to sort by MostRecentComment fields (e.g. sort BlogEntry results reverse-chronologically by MostRecentComment.created.

维护一个额外的外键,BlogEntry.most_recent_comment_id.维护起来很烦人,并且破坏了Cake的ORM:含义为BlogEntry belongsTo MostRecentComment.可以,但是看起来...不对.

Maintaining an additional foreign key, BlogEntry.most_recent_comment_id. This is annoying to maintain, and breaks Cake's ORM: the implication is BlogEntry belongsTo MostRecentComment. It works, but just looks...wrong.

这些解决方案迫切需要解决,因此前几天我坐下来讨论了这个问题,并研究了一个更好的解决方案.我已经在下面发布了最终的解决方案,但我很高兴(也许只是一个小问题而已),发现有一些令人难以置信的简单解决方案一直困扰着我.或其他符合我标准的解决方案:

These solutions left much to be desired, so I sat down with this problem the other day, and worked on a better solution. I've posted my eventual solution below, but I'd be thrilled (and maybe just a little mortified) to discover there is some mind-blowingly simple solution that has escaped me this whole time. Or any other solution that meets my criteria:

  • 它必须能够按Model::find级别的MostRecentComment字段进行排序(即,不只是对结果的提示);
  • commentsblog_entries表中不应要求其他字段;
  • 它应该尊重CakePHP ORM的精神".
  • it must be able to sort by MostRecentComment fields at the Model::find level (ie. not just a massage of the results);
  • it shouldn't require additional fields in the comments or blog_entries tables;
  • it should respect the 'spirit' of the CakePHP ORM.

(我也不确定这个问题的标题是否尽可能简洁/翔实.)

(I'm also not sure the title of this question is as concise/informative as it could be.)

推荐答案

我开发的解决方案如下:

The solution I developed is the following:

class BlogEntry extends AppModel
{
    var $hasMany = array( 'Comment' );

    function beforeFind( $queryData )
    {
        $this->_bindMostRecentComment();

        return $queryData;
    }

    function _bindMostRecentComment()
    {
        if ( isset($this->hasOne['MostRecentComment'])) { return; }

        $dbo = $this->Comment->getDatasource();
        $subQuery = String::insert("`MostRecentComment`.`id` = (:q)", array(
            'q'=>$dbo->buildStatement(array(
                'fields' => array( String::insert(':sqInnerComment:eq.:sqid:eq', array('sq'=>$dbo->startQuote, 'eq'=>$dbo->endQuote))),
                'table'  => $dbo->fullTableName($this->Comment),
                'alias'  => 'InnerComment',
                'limit'  => 1,
                'order'  => array('InnerComment.created'=>'DESC'),
                'group'  => null,
                'conditions' => array(
                    'InnerComment.blog_entry_id = BlogEntry.id'
                )
            ), $this->Comment)
        ));

        $this->bindModel(array('hasOne'=>array(
            'MostRecentComment'=>array(
                'className' => 'Comment',
                'conditions' => array( $subQuery )
            )
        )),false);

        return;
    }

    // Other model stuff
}

这个概念很简单. _bindMostRecentComment方法定义了一个相当标准的has-one关联,它在关联条件中使用子查询来确保只有最新的Comment才加入BlogEntry查询.该方法本身在任何Model::find()调用之前被调用,可以对每个BlogEntry的MostRecentComment进行过滤或排序.

The notion is simple. The _bindMostRecentComment method defines a fairly standard has-one association, using a sub-query in the association conditions to ensure only the most-recent Comment is joined to BlogEntry queries. The method itself is invoked just before any Model::find() calls, the MostRecentComment of each BlogEntry can be filtered or sorted against.

我意识到可以在hasOne类成员中定义此关联,但是我不得不写一堆原始SQL,这让我停顿了.

I realise it's possible to define this association in the hasOne class member, but I'd have to write a bunch of raw SQL, which gives me pause.

我本来希望从BlogEntry的构造函数中调用_bindMostRecentComment,但是(根据文档)使绑定永久化的Model :: bindModel()参数似乎不起作用,因此绑定必须在beforeFind回调中完成.

I'd have preferred to call _bindMostRecentComment from the BlogEntry's constructor, but the Model::bindModel() param that (per the documentation) makes a binding permanent doesn't appear to work, so the binding has to be done in the beforeFind callback.

这篇关于在CakePHP中定义两个模型之间同时具有多个和具有一个关联的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆