【问题标题】:CakePHP HABTM FilteringCakePHP HABTM 过滤
【发布时间】:2010-12-21 17:32:15
【问题描述】:

我有两张表 - usersservers,对于 HABTM 关系,users_servers。用户 HABTM 服务器,反之亦然。

我正在尝试为 Cake 找到一种方法来选择分配给用户的服务器。

我正在尝试像$this->User->Server->find('all'); 这样的东西,它只返回所有服务器,不管它们是否属于用户。

$this->User->Server->find('all', array('conditions' => array('Server.user_id' => 1))) 只是给出了一个未知的列 SQL 错误。

我确定我遗漏了一些明显的东西,但只需要有人指出我正确的方向。

谢谢!

【问题讨论】:

    标签: php mysql cakephp cakephp-1.3 has-and-belongs-to-many


    【解决方案1】:

    您的表名是正确的。有很多方法可以做到这一点:

    使用 Containable 行为

    在您的 AppModel 中,设置以下内容:

     var $recursive = -1;
     var $actsAs = array('Containable');
    

    然后,使用以下代码查询您的服务器:

    $userWithServers = $this->User->find('all', array(
        'conditions' => array('User.id' => 1),
        'contain' => array('Server')
    ));
    

    请注意,我们查询的是用户模型,而不是服务器模型来完成此操作。

    使用 bindModel

    $this->Server->bindModel(array('hasOne' => array('UsersServer')));
    $this->Server->find('all', array(
        'fields' => array('Server.*'),
        'conditions' => array('Server.user_id' => 1)
    ));
    

    我个人不建议大量使用 bindModel。最终,您的代码变得有点难以管理。您应该尽可能尝试使用 Containable 行为。代码看起来更简洁。更多关于 bindModel 方法的内容可以在here找到。

    HTH。

    【讨论】:

    • 可包含的行为正是我想要的。谢谢!
    【解决方案2】:

    我认为您应该将游览表命名为 user_servers。

    【讨论】:

    • 看蛋糕手册我认为我的方法应该有效? This new join table's name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ ).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多