php - CakePHP - 第三部分作业

标签 php mysql cakephp cakephp-model

很抱歉,如果标题没有达到我的目的,但不知道如何命名。这是我的任务:

我有一个购物车,包含多个属于价格 (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');
}

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

我在这里缺少什么?

/编辑:最近的更改:

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

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

最佳答案

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

我更喜欢使用 AppModel 启用的可容纳行为:

var $actsAs = array('Containable');

然后你可以这样做:

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

关于php - CakePHP - 第三部分作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651606/

相关文章:

php - 我想将背景图片放入 Laravel 元素的 Blade 中

php - 如何使用 GET 或 POST 方法将变量传递到 php 中的另一个页面?

php - Mysql 地理空间搜索返回奇怪的结果

php - 如何使用 Codeigniter 在 PHP 中创建具有 2 个或更多条件的 foreach?

php - cakephp 插入不同的表

mysql - CakePHP 2.5.1 中无法将数据从一个表单保存到多个表中

php - CakePHP Auth 允许 JSON 扩展

php - Doctrine 2 - i18n 的最佳实践?

javascript - 如何使用 Ajax 在单击按钮时将值发布到 Controller 函数并同时重定向到新页面?

mysql 删除出现数字后的所有内容(包括数字)