cakephp模型关联/加入相同的表 [英] cakephp model association/join with same table

查看:92
本文介绍了cakephp模型关联/加入相同的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含父母和孩子的表格。我想要能够建立模型,以便它返回父母和他们的孩子,即它与自己相关联。

I have a table that contains parents and children. I want to be able to build the model so that it returns the parents and their children i.e it associates with itself.

ID Name ParentID
1  Parent  0
2  Child1  1
3  Child2  1
4  Parent2 0
5  Child3  4

我使用以下SQL

SELECT
 grp2.id,
 grp2.name
FROM wp_bp_groups grp1
LEFT JOIN wp_bp_groups grp2
 ON grp2.parent_id = grp1.id
WHERE grp1.id = '$parent_id'
ORDER BY grp2.name


推荐答案

尝试这样:

<?php  
class Group extends AppModel { 

 var $name = 'Group'; 

 var $belongsTo = array( 
        'ParentGroup' => 
            array('className' => 'Group', 
                  'foreignKey' => 'parent_id' 
        ), 
     ); 

 var $hasMany = array( 
    'ChildGroup' => 
            array('className' => 'Group', 
                  'foreignKey' => 'parent_id' 
            ), 
    ); 
} 
?>

这篇关于cakephp模型关联/加入相同的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆