如何在CakePHP中执行连接?
如何在CakePHP中执行连接,例如下面针对MySQL的连接如何在CakePHP中执行连接?,php,cakephp,join,Php,Cakephp,Join,如何在CakePHP中执行连接,例如下面针对MySQL的连接 SELECT * FROM yarns y JOIN yarn_brands yb JOIN contents ct WHERE y.id = ct.yarn_id AND yb.id = y.yarn_brand_id AND ct.material_id = 2 我试着四处寻找答案,但没有找到任何有效的方法。 我发现了一些关于“contain”的信息,我尝试了这个方法,但是我得到的结果是,它生成的查询没有包含请求加入的表的联接
SELECT *
FROM yarns y
JOIN yarn_brands yb
JOIN contents ct
WHERE y.id = ct.yarn_id
AND yb.id = y.yarn_brand_id
AND ct.material_id = 2
我试着四处寻找答案,但没有找到任何有效的方法。
我发现了一些关于“contain”的信息,我尝试了这个方法,但是我得到的结果是,它生成的查询没有包含请求加入的表的联接
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
CakePHP使所有这些都变得非常简单,前提是您已经阅读了关于模型关系的书,并相应地设置了模型和数据库表。这是CakePHP的一个非常重要的部分,它将构成许多应用程序。如果你懂得如何用“蛋糕”的方式来做这件事,它会让你的生活更轻松 对于MySQL示例,请尝试以下代码。显然,我不知道您的模型关系是什么,但这里有一个基于MySQL的猜测
// app/Model/Yarn.php
class Yarn extends AppModel {
public $belongsTo = array('YarnBrand');
// You might need this as $hasOne instead, I can't tell from the MySQL alone.
public $hasMany = array('Content');
}
// app/Model/YarnBrand.php
class YarnBrand extends AppModel {
public $hasMany = array('Yarn');
}
// app/Model/Content.php
class Content extends AppModel {
public $belongsTo = array('Yarn');
}
用于查找所有纱线及其纱线和内含物的代码
$this->Yarns->find('all', array(
'conditions' => array(
Content.material_id' => 2
),
'contain' => array(
'YarnBrand',
'Content'
)
));
这就是我最终得到的加入:
$options['contain'] = '';
$options['joins'][0]['table'] = 'contents';
$options['joins'][0]['alias'] = 'cont';
$options['joins'][0]['conditions'] = 'Yarn.id = cont.yarn_id';
$options['joins'][1]['table'] = 'yarn_brands';
$options['joins'][1]['alias'] = 'yb';
$options['joins'][1]['conditions'] = 'yb.id = Yarn.yarn_brand_id';
$options['fields'] = array('Yarn.name');
$options['conditions']['cont.material_id'] = $this->request->data['Yarn']['material_id'];
$options['conditions']['Yarn.yarn_brand_id'] = $this->request->data['Yarn']['yarn_brand_id'];
我相信这个模型也必须有
可包含的行为才能工作…谢谢你的回答!模型和它的“关系”正是我所拥有的,我用蛋糕烘焙我的模型、视图和控制器,除了这个连接,一切都很好。当我尝试find()时,我得到一个错误:“SQLSTATE[42S22]:Column not found:1054未知列'Content.material_id'位于'where子句'中”。由于评论空间不足,我无法在这里发布它生成的整个sql语句。如果我删除了“条件”部分,但得到了一个结果。@Hoff:我已经将Containable附加到模型:public$actsAs=array('Containable');同样值得一提的是我上面发布的错误,在数据库的Contents表中有一个“material_id”列