【问题标题】:CakePHP - Find parent based on childCakePHP - 根据孩子查找父母
【发布时间】:2012-09-20 22:14:34
【问题描述】:

我有三张表公司、产品和价格。

Companies hasMany Products
Products hasMany Prices

我目前正在尝试在这些表格中搜索低于某个价格的产品,我正在尝试的代码是:

$results = $this->Product->find('all', array(
    'conditions' => array(
        'Price.price <=' 10
    )
));

由于某种原因使用这个代码 cakephp 这会带来一个错误:

Unknown column 'Price.price' in 'where clause'

我认为这是因为产品有多个价格(它加入的是公司表而不是价格表),谁能告诉我为什么会出错并知道如何让它工作?

注意:完成这项工作后,我希望能够根据价格和产品表中的条件查找产品,然后在结果页面中显示所有 3 个数据。

我想过先搜索价格表,然后搜索产品表,但我相信一定有更有效的方法?

【问题讨论】:

  • $this-&gt;Product-&gt;Price-&gt;find('all', array('conditions'=&gt;array('Price.price &lt;=' =&gt; 10))); ?您应该能够通过关联访问所需的所有数据。

标签: php mysql cakephp


【解决方案1】:

您可以对这些类型的查询使用 adhoc-joins。 Cake 不会为 1:n 或 n:n 关系进行连接,因此您必须手动指定它。

$results = $this->Product->find('all', array(
    'joins' => array(
        array(
            'alias' => 'Price',
            'table' => 'prices',
            'foreignKey' => false,
            'conditions' => array('Price.product_id = Product.id'),
        ),
    ),
    'conditions' => array(
        'Price.price <=' => 10,
    ),
));

【讨论】:

    【解决方案2】:

    在你的位置我会这样做:

    $results = $this->Product->Price->find('all', array(
        'recursive' => 2,
        'conditions' => array(
            'Price.price <=' => 10
        )
    ));
    

    HasMany 不加入表,但 belongsTo 可以。

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多