dongpu2694 2010-12-21 17:32
浏览 47
已采纳

CakePHP HABTM过滤

I've got two tables - users and servers, and for the HABTM relationship, users_servers. Users HABTM servers and vice versa.

I'm trying to find a way for Cake to select the servers that a user is assigned to.

I'm trying things like $this->User->Server->find('all'); which just returns all the servers, regardless of whether they belong to the user.

$this->User->Server->find('all', array('conditions' => array('Server.user_id' => 1))) just gives an unknown column SQL error.

I'm sure I'm missing something obvious but just need someone to point me in the right direction.

Thanks!

  • 写回答

2条回答 默认 最新

  • douliao8402 2010-12-22 03:50
    关注

    Your table names are right. There are many ways to do this:

    Use the Containable behavior

    In your AppModel, set the following:

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

    Then, use the following code to query your servers:

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

    Note that we are querying the User model, instead of the Server model to accomplish this.

    Use bindModel

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

    I personally don't recommend using bindModel a lot. Eventually, your code becomes a bit unmanagable. You should try using the Containable behavior whenever possible. The code looks cleaner and simpler. More on the bindModel method can be found here.

    HTH.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?