【问题标题】:CakePHP 2.0 - How to remove join tables from containableCakePHP 2.0 - 如何从可包含的连接表中删除
【发布时间】:2011-10-31 18:23:26
【问题描述】:

我在这样的操作中使用 Containable:

public function index()
{
    $this->User->recursive = -1;
    $this->User->Behaviors->load('Containable');

    if ($this->RequestHandler->accepts('xml'))
    {
        $this->set('users', array("Users" => array("UserEntry" => $this->User->find('all',
            array(
                'fields' => array('User.id','User.username', 'User.email', 'User.created', 'User.modified'),
                'contain' => array(                        
                    'Group' => array(
                        'fields' => array('Group.id','Group.name','Group.created'),
                    )
                )
            )            
        ))));
    }
    else if ($this->RequestHandler->accepts('json'))
    {
    }
    else if ($this->RequestHandler->accepts('html'))
    {
        $this->set('users', $this->paginate());
    }
}

它获取了我需要的所有数据,但有一件事我无法弄清楚。用户和组之间存在 HABTM 关系,连接表 users_groups。我正在将 find('all') 的输出序列化为 Xml 以用于视图中的 REST Api。问题是数据包含嵌套在我的“Groups”数组中的额外“GroupsUser”数组。 Api 的用户不需要知道连接表信息,所以我想删除它。当前输出如下所示:

index.ctp

<?php
    //debug($users);

    $xml = Xml::build($users, array('return' => 'domdocument'));
    echo $xml->saveXML();
?>

index.ctp 的输出 -> http://www.pastie.org/2789367

看到嵌套在 Group 标签中的 GroupsUser 标签了吗?这就是我要删除的内容。如果没有一个很好的简单方法来做到这一点,我将使用视图中的一些循环手动构建 xml,或者在模型中创建我自己的 find 方法并在 GroupsUser 上使用 unset()。这两种解决方案都不理想,所以我希望这里有人有更好的解决方案。 :)

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    我你肯定一切都在一个连接中完成(只属于关联)你可以使用带有自动字段的可包含组件,像这样

    $this->Post->Behaviors->attach('Containable', array('autoFields' => false));
    

    (这是在控制器部分动态附加它。

    如果您的 find 具有 hasMany 关联,您将有 2 个查询,而不是因此 cake 需要获取此字段以执行连接。在这种情况下,您也可以使用可链接组件,将所有内容放入连接中,而不是进行大量查询,让您有机会仅选择所需的字段。

    这是linkable component的链接

    【讨论】:

    • 我有连接表的原因是因为它是一个 HABTM 关系。我试过可链接但没有留下深刻的印象。实际上只是在 find() 选项中使用“加入”功能的一种更简单的方法。我认为不加入 users_groups 表就不可能获取数据。不过感谢您的回复。
    猜你喜欢
    • 2012-10-23
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2019-12-15
    • 2012-03-27
    • 2016-02-19
    • 2012-01-30
    相关资源
    最近更新 更多