CakePHP中如何让Containable行为与Tree行为配合

In CakePHP how to make Containable behavior cooperate with Tree behavior

我对 containable 有这个问题,我的 Categories 模型表现得像一棵树:

class Category extends AppModel {
  public $actsAs = ['Tree', 'Containable'];

  public $hasMany = [
    'Novelty' => [
      'className' => 'Novelty',
      'foreignKey' => 'category_id',
      'dependent' => false,
    ]
  ]
}

其结构:

Category(
  id int(11)
  name varchar(255)
  parent_id int(11)
  lft int(11)
  rght int(11)
)

我有一个 Novelty 模型:

class Novelty extends AppModel {
  public $actsAs = ['Containable'];

  public $belongsTo = [
    'Category' => [
      'className' => 'Category',
      'foreignKey' => 'category_id',
    ]
  ];
}

新颖结构:

Novelty(
  id int(11)
  name varchar(255)
  category_id int(11)
)

协会

Category -> hasMany -> Novlety
Novelty -> belongsTo -> Category

find('threaded') 中的类别示例结构如下:

['Category'] => [
  'id' => 13
  'name' => 'Main'
  'lft' => 88
  'rght' => 105
  'children' => [
    [0] => [
      ['Category'] => [
        'id' => 131
        'name' => 'sub1'
        'lft' => 89
        'rght' => 90
      ]
    ]
    [1] => [
      ['Category'] => [
        'id' => 132
        'name' => 'sub2'
        'lft' => 91
        'rght' => 92
      ]
    ]
    [...]
  ]
]

现在当我尝试 containable 时:

$this->Category->contain(
  'Novelty' => [
    'conditions' => [
      'AND' => [
        'Novelty.category_id >=' => 13,
        'Novelty.category_id !=' => 14
      ]
    ]
  ]
);

现在当我 运行 Category->find('all') 结果中没有新奇的东西。因为蛋糕加了自己的条件Novelty.category = (13)。我无法摆脱也无法扩展它。所以查询看起来像这样:

SELECT `Novelty`.`id`, `Novelty`.`name`, `Novelty`.`category_id`, 
FROM `databse`.`novelties` AS `Novelty` 
WHERE ((`Novelty`.`category_id` >= 13) 
  AND (`Novelty`.`category_id` < 14)) 
  AND `Novelty`.`category_id` = (13)

是否有修改默认查询条件的特殊条件?

我的目标:

要获得与子类别相关的新奇事物,而不仅仅是那些与主类别相关的新奇事物。 但这有可能吗?

Now when i run Category->find('all') there are no Novelties in result. Because cake adds its own condition Novelty.category = (13). And I can't get rid nor expand it. So query looks like this:

这是代码的正确行为。您有一个 Cateogry hasMany Novelty 关联,为了实现这一点,Cake 添加了条件。

对我来说,您似乎想要查找所有新奇记录,除了 类别 ID 14 的记录,对吗?

临时 unbindModel() 你的 Novelty 关联并将其作为没有外键但有条件的 hasOne 关联添加回来:

['conditions' => ['Novelty.cateogry_id !=' 14]]

或者使用the joins array的查询。