我是CakePHP的新手,我在构建一个要学习的示例时遇到了问题。
我正在构建一个带有3个模型的插件(Categoria,Plato,Imagen)
它们之间的关系如下:范畴-柏拉图(n-n)柏拉图-想象(1-n)
如果我进入柏拉图视图,我通过关系得到所有的图像,但当我通过一个类别访问时,我不能仅仅到达与每个柏拉图相关的图像。为什么?有什么问题吗?
模型代码:
柏拉图:
App::uses('AppModel', 'Model');
class Plato extends ErestaurantAppModel {
public $name = 'Plato';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Categoria' => array(
'className' => 'Categoria',
'joinTable' => 'categorias_platos',
'foreignKey' => 'plato_id',
'associationForeignKey' => 'categoria_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
public $hasMany = array('Imagen' =>
array('foreingkey' => array('plato_id')));
}类别:
App::uses('AppModel', 'Model');
class Categoria extends ErestaurantAppModel {
public $name = 'Categoria';
//public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Plato' => array(
'className' => 'Plato',
'joinTable' => 'categorias_platos',
'foreignKey' => 'categoria_id',
'associationForeignKey' => 'plato_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
)
);
}图像:
App::uses('AppModel', 'Model');
class Imagen extends ErestaurantAppModel {
public $name = 'Imagen';
//public $actsAs = array('Containable');
public $belongsTo = array('Plato');
}最后,我在进入Categoria视图时启动的代码。
App::uses('AppController', 'Controller');
class CategoriasController extends ErestaurantAppController {
public $uses = array('Erestaurant.Categoria');
public function index() {
$this->Categoria->recursive = 0;
$this->set('data', $this->Categoria->find('all'));
}
public function view($id = null) {
if (!$this->Categoria->exists($id)) {
throw new NotFoundException(__('Registro inválido.'));
}
/*
$this->Categoria->recursive = -1;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id),
'contain' => array(
'Plato' => array(
'Imagen'
)
)
);
*/
$this->Categoria->recursive = 2;
$options = array('conditions' =>
array('Categoria.'.$this->Categoria->primaryKey => $id));
$this->set('item', $this->Categoria->find('first', $options));
}
}注释代码你可以看到,这是我尝试的另一种方式,使用了Containable,但最后我得到了错误"Plato is not associated with model Imagen“
数据库看起来一切正常,每个表都是根据需要创建的(categorias,platos,imagens,categorias_platos),并且创建了所有的关键字,并试图保留CakePHP的默认名称。
谢谢!
发布于 2014-06-26 19:30:15
要访问深层关系,您必须使用可包含行为。您的模型中有一个可包含行为的定义,但由于某种原因,它被注释了。
public $actsAs = array('Containable');在你的Categoria中取消对这一行的注释,你可以这样访问深层关系:
$this->Categoria->find('all', array(
'contain'=>array(
'Plato.Imagen'
)
));...or类似这样的东西。如需更多信息,请访问此链接Containable Behavior
https://stackoverflow.com/questions/24425963
复制相似问题