0

我有如图所示的模型(http://hosting5578581.az.pl/img/association.png),我可以弄清楚如何获取数据(在 ORDER 模型中),如图所示,我可以从 OrderItems 项目中获取与某些订单相关,但我不知道如何在 mysql 查询中将其显示为 NAME(在 Items 表中)我可以通过(例如 order_id=1)来执行此操作:

select items.name from order_items, items WHERE order_items.item_id = items.item_id AND order_items.order_id = 1;

4

3 回答 3

2

你会想要使用CakePHP 的 Containable Behavior

它有很好的文档记录(单击上面的链接),并允许您提取所需的任何相关数据。

注意:您应该几乎只使用CakePHP 的 find()而不是您自己的自定义 MySQL 查询。

它最终看起来像这样:

$this->Order->find('first', array(
    'conditions' => array(
        'id' => $orderId
    ),
    'contain' => array(
        'Customer',
        'OrderItem' => array(
            'Item'
        )
    )
));
于 2013-08-20T18:42:57.650 回答
0

@Dave: In my OrdersController i have code:

$products = $this->Order->find('first', array(

            'contain' => array (
                'Customer',
                'OrderItem' => array(
                    'Item'
                )
            )
                 ));

after find() query i get this result (i omit array 'Order' and 'Customer' - are no important now):

array(

'OrderItem' => array(
        (int) 0 => array(
            'order_id' => '1',
            'item_id' => '4',
            'quantity' => '2',
            'Item' => array()
        ),
        (int) 1 => array(
            'order_id' => '1',
            'item_id' => '6',
            'quantity' => '1',
            'Item' => array()
        ),
        (int) 2 => array(
            'order_id' => '1',
            'item_id' => '7',
            'quantity' => '1',
            'Item' => array()
        ),
        (int) 3 => array(
            'order_id' => '1',
            'item_id' => '8',
            'quantity' => '1',
            'Item' => array()
        )
    )
)

1.So how can I get all 'products' now ? i started with something similar to this but i know that it is bad because i must write ['0']...['1]... which is dynamic variable

<?php echo h($products['OrderItem']['0']['item_id']); ?>

2.As you can see

'Item' => array()

is null ;-) so i cant get for example the name of the item from a Item table/model

于 2013-08-29T12:06:06.737 回答
0

如果我理解你的问题,你需要一些方法:

$this->recursive = 2;   
$this->read(null, $id);

其中 id 是订单数

于 2013-08-20T18:26:23.180 回答