cakephp - Cakephp 2.8 从三个表中提取数据,每对表一个公共列
问题描述
我有三个表,我想知道什么是正确的 Find 命令,可以根据选择的类别提取正确的汽车型号。
Category table
---------------------
Cat_ID Category
1 Sedan
2 SUV
3 Truck
Manufacturers tables
--------------------------
CAR_ID Cat_ID Manufacturer
1 1 BMW
2 1 BMW
3 2 Mercedes
4 3 Dodge
Model table
--------------
CAR_ID Model
1 i320
2 i540
3 GL320
4 RAM
我能够根据制造商拉出合适的汽车,但是当我尝试根据类别拉出汽车时它不起作用。
$catid='Sedan';
$car_id = $this->car->find('all',array('fields' => array('car.id'),'conditions' => array('car.category_id' => $catid),'order' => array('car.id' => 'desc')));
$models = $this->Model->find('all',array('conditions' => array('Model.car_id'=>$car_id),'order' => array('Model.id' => 'desc')));
如果我选择轿车,我希望输出显示宝马 i32 和 i520 车型。
解决方案
使用连接语句
我不知道您使用的是什么版本的 cakephp,但我使用的是 cakephp 2.0。
$this->Model->find('all',[
'joins' => [
[
'table' => 'Manufacturers',
'alias' => 'Manufacturers',
'type' => 'LEFT',
'conditions' => [
'Category.Cat_ID = Manufacturers.Cat_ID'
]
],
[
'table' => 'Model',
'type' => 'LEFT',
'conditions' => [
'Model.CAR_ID = Manufacturers.CAR_ID'
]
]
]
]);
如果您想限制您将使用的类别,请使用如下条件
$this->Model->find('all',[
'joins' => [
[
'table' => 'Manufacturers',
'alias' => 'Manufacturers',
'type' => 'LEFT',
'conditions' => [
'Category.Cat_ID = Manufacturers.Cat_ID'
]
],
[
'table' => 'Model',
'type' => 'LEFT',
'conditions' => [
'Model.CAR_ID = Manufacturers.CAR_ID'
]
]
],
'conditions' => [
'Category.Cat_ID' => 1
]
]);
旁注:使用 '[]' 和 array() 在技术上是相同的,但是,这里是使用 array() 的示例代码。
$this->Category->find('all',
array(
'joins' => array(
array(
'table' => 'Manufacturers',
'alias' => 'Manufacturers',
'type' => 'LEFT',
'conditions' => array(
'Category.Cat_ID = Manufacturers.Cat_ID'
)
),
array(
'table' => 'Model',
'type' => 'LEFT',
'conditions' => array(
'Model.CAR_ID = Manufacturers.CAR_ID'
)
),
),
'conditions' => array(
'Category.Cat_ID' => 1
)
));
更新 2
$this->Model->find('all',
array(
'joins' => array(
array(
'table' => 'Manufacturers',
'alias' => 'Manufacturers',
'type' => 'LEFT',
'conditions' => array(
'Model.Car_ID = Manufacturers.Car_ID '
)
),
array(
'table' => 'Category',
'type' => 'LEFT',
'conditions' => array(
'Category.Cat_ID= Manufacturers.Cat_ID'
)
),
),
'conditions' => array(
'Category.Cat_ID'=>$cat_id
)
));
推荐阅读
- database - Laravel 如何从“文章”表中获取没有类别的所有记录?
- html - 输入复选框无法点击
- php - Laravel 模型 ON 方法
- javascript - 使用挂钩根据变量值更新状态对象?
- python - 调用子方法时如何强制执行父方法调用?
- jquery - Extjs 4.1.0 组合框侦听从 ajax 调用完全加载的先前组合框值
- r - 在点 p1 周围创建几个点,到该点具有指定的距离。算法错误
- c# - 寻找一种更有效的方式在 startup.cs 和控制器中添加我的存储库
- deep-learning - ValueError: 层序贯_3 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:(无,180)
- docker - docker compose 中的主机和端口转发