【问题标题】:CakePHP - Third Part AssignmentsCakePHP - 第三部分作业
【发布时间】:2013-09-06 06:49:06
【问题描述】:

对不起,如果标题错过了我的目标,但不知道如何命名。这是我的任务:

我有一个购物车,其中包含属于价格 (1:1) 的多个项目 (1:n)。

商品和价格之间的关系也很有效:

class Item extends AppModel {

    public $hasOne = 'Price';
}

class Price extends AppModel {

public $belongsTo = array(
    'Item' => array(
                'className' => 'Item',
                'foreignKey' => 'id'
            )
    );
}

但现在我选择(查找)一个购物车并希望包含这些物品,这也可以:

class CartItem extends AppModel {

    public $useTable = 'cart_items';

    public $belongsTo = array('Item', 'Address');
}

但我真正需要的是获取每个项目的价格,这是行不通的(项目模型中的 afterFind()-回调中的 $result 不包括分配的价格和价格模型中的 afterFind()-回调查找购物车时不调用)..

我在这里错过了什么?

/EDIT:最近的变化:

class AppModel extends Model {
    var $actsAs = array('Containable');
}


class CartsController extends AppController {

public function getCart() {
$cart = ClassRegistry::init('CartItem')->find('all', array(
                    'contain' => array(
                        'Item' => array(
                            'Price'
                        ),
                        'Address'
                    ),
                    'conditions' => array(
                        'id_cart' => $cart['Cart']['id']
                    )
                ));
}

上述更改导致我会在找到的项目中获得价格,但只会在找到的最后一个中获得价格。

【问题讨论】:

    标签: php mysql cakephp cakephp-model


    【解决方案1】:

    您没有显示您的实际find(),但我怀疑您没有设置适当的'recursive' 参数或没有使用'contain'

    我更喜欢使用从 AppModel 启用的可包含行为:

    var $actsAs = array('Containable');
    

    然后你可以这样做:

    $cartItem = $this->CartItem->find(
      'first',
      array(
        'contain' => array(
          'Item' => array(
            'Price'
          ),
          'Address'
        ),
        'conditions' => array('CartItem.id' => 123)
      )
    );
    

    【讨论】:

    • 非常感谢,这部分工作。 - 但是:在 5 个项目中,只有最后一个选择的项目现在包含价格。查看我的代码,我插入了更改和 FIND
    • 在 Price 与 Item 的 $belongsTo 关系中,您使用的 foreignKey 为“id”,这通常是“item_id”。如果您确实没有外键并且强制 Item 和 Price 具有相同的 id 值,那么在 Item 的 $hasOne for Price 中您还需要指定外键,因为 CakePHP 将期望找到 Price.item_id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多