CakePHP得到了协会的关联

时间:2018-01-19 11:23:18

标签: php cakephp associations

我有一个OffersTo Products表的Offers表。 Products表属于标记表(使用外键:markup_id)。

现在,当我尝试这段代码时:

$offersObject = $this->paginate($this->Offers->find('all')
                ->contain('Products');

我得到了结果:

Array
(
    [0] => App\Model\Entity\Offer Object
        (
            [id] => 1
            [store_id] => 1
            [product_id] => 1
            [price] => 150
            [new_price] => 0
            [status] => 1
            [twid] => 70261
            [magkod] => MAG
            [product] => App\Model\Entity\Product Object
                (
                    [id] => 1
                    [name] => BOSCH S3 41Ah 360A S3001
                    [markup_id] => 3
                    [created] => Cake\I18n\FrozenTime Object
                        (
                            [time] => 2018-01-08T14:30:38+00:00
                            [timezone] => UTC
                            [fixedNowTime] => 
                        )

                    [modified] => Cake\I18n\FrozenTime Object
                        (
                            [time] => 2018-01-08T14:30:38+00:00
                            [timezone] => UTC
                            [fixedNowTime] => 
                        )


                    [[repository]] => Products
                )
        )

问题是我真的得到了markup_id,我需要的是Products表中的关联行。

来自我的OffersTable.php:

    $this->belongsTo('Products', [
        'foreignKey' => 'product_id',
        'joinType' => 'INNER'
    ]);

ProductsTable.php

    $this->hasMany('Offers');

    $this->belongsTo('Markups', [
        'foreignKey' => 'markup_id',
        'joinType' => 'INNER'
    ]);

请指教。或者要求任何澄清。

1 个答案:

答案 0 :(得分:2)

您可以使用嵌套数组加载嵌套关联:

$offersObject = $this->paginate($this->Offers->find('all')
                ->contain([
                    'Products' => [
                        'Markups'
                    ]
                ]);

或者,您可以使用点表示法表达嵌套关联:

$offersObject = $this->paginate($this->Offers->find('all')
                    ->contain([
                        'Products.Markups'
                    ]);

Eager Loading Associations Via Contain