很抱歉,如果标题没有达到我的目的,但不知道如何命名。这是我的任务:
我有一个购物车,包含多个属于价格 (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/