我的数据库中有2个表,第二个(订单)表有这些第一(书)表主键的foreign_key
Books
----+---------+-------------
id | slug | name |
----+---------+--------------
1 | math | mathematics |
----+---------+--------------
2 | physics | holidays |
-----------------------------
Orders
----+---------+-------+--------
id | book_id | count | price |
----+---------+-------+--------
1 | 2 | 12 | 100000 |
--------------------------------
我想要下面的结果
result
----+---------+----------+----------+----------+------------------
id | book_id | slug | name | order_id | count | price |
----+---------+----------+----------+-----------------------------
1 | 2 | physics | holidays | 1 | 12 | 100000 |
------------------------------------------------------------------
答案 0 :(得分:0)
我相信每件产品都有价格。首先,将PRODUCT表与PRICE相关联。 在蛋糕中这很容易做到:
模型中的(Product.php
)
class Product extends AppModel{
public $hasMany = array('Price');
}
Price.php
中的
class Price extends AppModel{
public $hasBelongTo = array('Product');
}
如果查询任何这些模型,在控制器中,返回的数组将包含两个模型的数据。
答案 1 :(得分:0)
建立如下关系
Product.php
....
public $hasMany = array(
'Price' => array(
'className' => 'Price',
'foreignKey' => 'product_id',
'dependent' => true,
'conditions' => '',
'group' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
....
Price.php
.....
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
....
然后在您的控制器中使用此查询
$this->Product->find('all',array('contain'=>array('Price')));