dpz3471 2014-07-25 16:37
浏览 35
已采纳

Cakephp Self refer Model不工作

I have a table

Medias:
    ID,
    PARENT_ID
    PATH
    TITLE

Items:
    ID
    medias
    Title
    description

Models

class ImageGallery extends AppModel {

    public $name = 'ImageGallery';
    public $useTable = "medias";

    var $belongsTo = array( 
        'Parent' => 
        array('className' => 'ImageGallery', 
            'foreignKey' => 'parent_id',
            'dependent' => false, 
        ), 
    );

    var $hasMany = array( 
        'Children' => 
        array('className' => 'ImageGallery', 
            'foreignKey' => 'parent_id',
            'dependent' => false,
        ), 
    ); 
}


class Item extends AppModel {

    public $useTable = "items";
    public $validate = array(
        'title' => array(
            'rule' => 'notEmpty'
        ),

    );

    public $belongsTo = array(

        'Gallery'   => array(
            'className' => 'ImageGallery', 
            'foreignKey'    =>  'medias'),
    );

    public $hasMany = array(
        'ItemMeta'  => array( 'className' => 'ItemMeta'),
    );
}

The media table contains gallery information. Images are stored in parent_id relation.

When I request Item->find('all'); I am getting only one entry from Media table, but I want to get all its children too. :(

I can get its children by using $this->ImageGallery->findById(10);, but I want to get them with the Item Model.

  • 写回答

1条回答 默认 最新

  • douchengjue9892 2014-07-25 16:57
    关注

    Use the containable behavior to specify which associated models you want the query to get. http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

    $this->Item->find('all', array('contain' => array('ImageGallery' => array('Children'))));
    

    If you're looking to go deeper than just the child level, like if you want to get the rest of the tree, then you'll need to either write something to recursively fetch the children, the children's children, etc., or perhaps you can alter your code and models to make use of CakePHP's Tree Behavior. See http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html and http://www.dereuromark.de/2013/02/17/cakephp-and-tree-structures/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路