CakePHP模型扩展关联
在查看InventoryCategory摘要时,我可以得到库存,但不能得到库存图像。CakePHP报告的错误是[Model“Inventory”与Model“InventoryImage”不关联]。以下是我使用的模型:CakePHP模型扩展关联,cakephp,model,model-associations,Cakephp,Model,Model Associations,在查看InventoryCategory摘要时,我可以得到库存,但不能得到库存图像。CakePHP报告的错误是[Model“Inventory”与Model“InventoryImage”不关联]。以下是我使用的模型: class InventoryCategory extends InventoriesAppModel { public $hasMany = array( 'Inventory' , 'InventoryCategoryImage
class InventoryCategory extends InventoriesAppModel {
public $hasMany =
array(
'Inventory'
, 'InventoryCategoryImage' => array
(
'className' => 'Media.MediaImage'
, 'foreignKey' => 'foreign_key'
, 'conditions' => array(
'InventoryCategoryImage.model' => 'InventoryCategoryImage'
, 'InventoryCategoryImage.group' => 'Inventory Category Image'
,
)
, 'dependent' => true
,
)
,
);
public function containedModels()
{
$contain = array(
'Inventory'
, 'InventoryCategoryImage'
,
);
return $contain;
}
}
class Inventory extends InventoriesAppModel {
public $belongsTo =
array(
'User'
, 'InventoryCategory'
,
);
public $hasMany =
array(
'InventoryImage' => array
(
'className' => 'Media.MediaImage'
, 'foreignKey' => 'foreign_key'
, 'conditions' => array(
'InventoryImage.model' => 'InventoryImage'
, 'InventoryImage.group' => 'Inventory Image'
,
)
, 'dependent' => true
, 'order' => 'InventoryImage.rank ASC, InventoryImage.id ASC'
)
,
);
public function containedModels()
{
$contain = array(
'User'
, 'InventoryCategory'
,
);
return $contain;
}
}
问题在于,通过在
InventoryCategory
中声明$hasMany
,可以替换并从其父类中删除$hasMany
数组
因此,$hasMany
声明还应该包含父级的关联,以便使其正常工作
另一种方法是将新关联附加到父级的$hasMany
数组中。这里的问题是:使用什么回调。我不知道(我也在寻找答案)。到目前为止,我认为
公共函数\uuu construct()
是最合适的
像这样:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct();
// adding Blog-specific Card-association.
// Blog is a class extending some other class that does not know about the Class association.
$this->belongsTo['Card'] = array(
'className' => 'Card',
'foreignKey' => 'card_id'
);
}
在find()调用中,
'recursive'=>2
?另外,请发布给您该错误的查找呼叫。否。我不使用递归。改为包含。code
public function view(){if(!$this->params['id']){$this->redirect($this->referer());}$conditions=(是数值($this->params['id'])?数组($this->modelClass.'.id='=>$this->params['id']):数组($this->modelClass.'.slug='>$this->params->['id'];$item=$this->{$this->modelClass}->find('first',array('conditions'=>$conditions',contain'=>$this->{$this->modelClass}->containedModels());$this->set(compact('item');}code