douzhi7754 2011-04-27 17:27
浏览 29
已采纳

当关系存在时,CakePHP连接表

I have a Message model that hasMany Librarian.

The problem I am having is that when I try to join a table to the Librarian table, that table has not been joined yet - i.e. the join I create appears before the relationship join is created.

$this->Message->find('all', array(
  'joins' => array(
    array(
      'table' => 'users',
      'alias' => 'User',
      'conditions' => array('User.id = Librarian.id')
    )
  )
));

This generates a query along these lines:

SELECT `Message`.`id`, `Message`.`librarian_id`, 
   `Message`.`Librarian`.`id`, `Librarian`.`user_id` 
    FROM `contact_messages` AS `Message` 
    INNER JOIN users AS `User` ON (`User`.`id` = `Librarian`.`user_id`) 
    LEFT JOIN `librarians` AS `Librarian` 
    ON (`Message`.`librarian_id` = `Librarian`.`id`)  
    WHERE `Message`.`id` = 3

I get the error

Unknown column 'Librarian.user_id' in 'on clause'

How can I join to a hasMany table after it has already been included in the build query?

Cheers

  • 写回答

2条回答 默认 最新

  • douyangquan2474 2011-04-27 17:51
    关注

    I tended to tackle this by actually binding a relationship into the code as I went along. It's a hacky method and quite old, very 1.2.

    This was using bindModel() which you can read about on here, http://book.cakephp.org/view/3/The-Manual#!/view/78/Associations-Linking-Models-Together

    The documentation for the model method is here, http://api12.cakephp.org/class/model#method-ModelbindModel

    The idea basically being that you can temporarily bind two models together even if no relationship exists, or if they have a distant relationship. I have done it, and it does work. I have some code somewhere, but not to hand.

    Also if you are using newer stuff, be sure to check out Containable() as this, as I understand it, encompasses a little more of the model's bindings. http://book.cakephp.org/#!/view/1323/Containable

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题