CakePHP找到HABTM [英] CakePHP find HABTM

查看:55
本文介绍了CakePHP找到HABTM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3种模型(用户消息标签)具有以下关系:

I have 3 models (User, Message and Tag) with the following relations:


  • User hasMany 消息

  • 消息 所属 用户

  • 消息 HABTM 标签

  • 标签 HABTM 消息

  • User hasMany Message
  • Message belongsto User
  • Message HABTM Tag
  • Tag HABTM Message

如果用户已登录,他可能希望查看所有 Message 标记了一些东西。

If a User is logged in he might want to see all Message tagged with something.

$messages = $this->Message->find('all', array(
    'conditions' => array("Message.user_id" => $this->uid),
    'contain' => array(
        'Tag' => array(
            'conditions' => array(
                'Tag.id' => $activetag['Tag']['id']
            )
         )
    ));

但是,此查找将返回该用户的所有消息。 (Conta两种模型都包含不正常的行为)

However, this find will return ALL messages of that user. (Containable behaviour is included in both models)

推荐答案

在子项(标签)上包含的内容不会在父项(消息)上执行过滤,这就是为什么所有消息都返回的原因。标签本身的可容纳的唯一放置条件,在您的情况下,仍将返回不匹配$ activeTag的消息,但附加空标签数组,而匹配的消息将返回仅包含一个标签的数组,即$ activeTag,但所有消息

Containable on child (tag) does not perform filter on the parent (message), that's why all the messages are returned. The containable only place condition on the tag itself, in your case, messages not matching $activeTag would still get returned but with empty tag array attached, while messages matching would return with an array containing only one tag, the $activeTag, but all messages would get returned.

出于您的目的,CakepHP建议使用join函数对HABTM进行过滤,它会自动为您加入hasOne或belongsTo,但涉及到HABTM时,您可能需要

For your purpose CakepHP recommend using join function for filtering with HABTM, it joins hasOne or belongsTo for you automatically but when it comes to HABTM you may need to perform the join yourself if needed.

假定表是按常规命名的:

assuming tables are named conventionally:

$this->Message->recursive = -1;

$options['joins'] = array(
    array('table' => 'messages_tags',
        'alias' => 'MessageTag',
        'type' => 'INNER',
        'conditions' => array(
            'Message.id = MessageTag.message_id',
        )
    ) );

$options['conditions'] = array(
    'MessageTag.tag_id' => $activetag['Tag']['id'],
    'Message.user_id' => $this->uid );

$message = $this->Message->find('all', $options);

此处有更多信息:
http://book.cakephp.org/2.0/en/models/associations-linking-models- together.html#joining-tables

这篇关于CakePHP找到HABTM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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