【问题标题】:How get data from Relationship tables如何从关系表中获取数据
【发布时间】:2015-08-03 14:20:46
【问题描述】:

我的数据库中有 2 个表,第二个(订单)表的外键是第一个(书)表的主键,如下所示

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  |
------------------------------------------------------------------

【问题讨论】:

    标签: database cakephp cakephp-2.0 relationship


    【解决方案1】:

    我相信每种产品都有价格。首先将 PRODUCT 表与 PRICE 相关联。 在蛋糕中,这很容易做到:

    在您的模型中 (Product.php)

    class Product extends AppModel{
       public $hasMany = array('Price');
    }
    

    Price.php

    class Price extends AppModel{
       public $hasBelongTo = array('Product');
    }
    

    在您的控制器中,如果您查询这些模型中的任何一个,则返回的数组将包含来自两个模型的数据。

    【讨论】:

      【解决方案2】:

      建立如下关系

      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')));
      

      【讨论】:

        猜你喜欢
        • 2021-08-06
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-09
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        相关资源
        最近更新 更多