如何在cakephp中实现自引用(parent_id)模型 [英] How to implement a self referencing (parent_id) model in cakephp

查看:139
本文介绍了如何在cakephp中实现自引用(parent_id)模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为categories的表。表格包含类别及其子(子类别)类别...

I have a table called categories. The table holds categories and their sub(subsub)categories...

这是一个简单的表格:


  • id

  • parent_id

  • title

这样我可以做出无限深度的类别...我希望cakephp会理解parent_id(我也尝试过category_id,但这使得cakePHP连接本身:D)

This way I can make categories with endless depth... I kinda hoped that cakephp would understand parent_id (I also tried category_id, but that makes cakePHP join on itself :D )

要解决这个问题的正确方法是什么?

What is the right way to tackle this?

注意:还有一个名为places的many to many表。这些地方可以属于一个或多个类别。

NOTE: There is also a 'many to many' table called places. Those places can belong to one or more categories.

推荐答案

你只需要像这样设置你的模型:

Tree behaviour is overkill for this situation. You just need to set your model up like this:

class Category extends AppModel {

  public $hasMany = array(
    'Children'=>array(
       'className'=>'Category',
       'foreignKey'=>'parent_id'
    )
  );

  public $belongsTo = array(
    'Parent'=>array(
       'className'=>'Category',
       'foreignKey'=>'parent_id'
    )
  );

}

现在,当你在Category上做一个find你会得到两个额外的模型称为父(指向父ID)和儿童(它列出它的孩子)。

Now, when you do a find() on Category, you'll get two additional Models called Parent (which points to the parent id) and Children (which lists it's children).

这篇关于如何在cakephp中实现自引用(parent_id)模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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