我正在使用Cake版本2.5.4 我有两张桌子。
一个由以下字段组成的调用arbols: id(int 11) nombre(varchar(255) especie:id(int 11)
名为fotos的第二个表包含以下字段:
id (int 11)
foto (varchar 255)
foto_dir (varchar 255)
arbol_id (int 11)
虽然Arbol模型与Especie模型有关, 我把它留给后者,因为它不是协商的理由。 Arbol模型与Foto模型有很多关系。
在Arbol模型中,我有以下内容:
public $hasMany = array(
'Foto'=> array(
'className' => 'Foto',
'foreignKey' => 'arbol_id',
'dependent' => true
)
);
In the Foto model I have the following:
public $belongsTo = array(
'Arbol'=> array(
'className'=>'Arbol',
'foreign_key'=>'arbol_id'
)
);
现在,在公共函数视图中的ArbolsController内部($ id = null) 我想做以下SQL查询:
SELECT * FROM arboles as a join fotos as f on a.id=f.arbol_id
所以我返回与视图中作为参数传递的特定树的id相关的所有照片 如果使用MySQL
完成此查询$registros=mysqli_query($conexion," select * from arboles as a join fotos as f on a.id=f.arbol_id")
它有效。 但是,如果我想以这种方式使用查询方法:
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
$registros = $this->Arbol->query("select * from arboles as a INNER JOIN fotos as f ON a.id=f.arbol_id");
它不起作用 阅读食谱我发现有一种方法可以加入。 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
我不理解她
如果你能向我解释,我将不胜感激。
非常感谢你!
答案 0 :(得分:0)
如果可以避免,则不应直接使用query
方法。
你可以做的是使用标准查找,将表加入containable(或linkable)。
这样的事情应该有效:
$registros = $this->Arbol->find('all', array(
'contain' => 'Foto'
));
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
答案 1 :(得分:0)
还有另一种方法可以加入cakephp中的表格,即自定义连接
创建要加入的表格数组,例如
$joins = array(
array(
'table' => 'fotos',//Table name
'alias' => 'Foto', //Model name
'type' => 'INNER', // type of join
'conditions' => array(
'Arbol.id = Foto.arbol_id'
) //Condition for join
)
);
$this->Arbol->find('all', array(
'joins' => $joins,
'conditions'=> array(Arbol.id => $id),
'fields' => array()
))
这将返回与id
相关的所有照片信息