代码之家  ›  专栏  ›  技术社区  ›  Michał Skrzypek

CakePHP获取关联

  •  0
  • Michał Skrzypek  · 技术社区  · 7 年前

    我有一个产品表下面的报价表。Products表属于Markups表(外键为:markup\u 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\u id,而我需要的是Products表中的关联行。

    从我的报价表。php:

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

    产品稳定。php

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

    请告知。或要求任何澄清。

    1 回复  |  直到 7 年前
        1
  •  2
  •   shahonseven    7 年前

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

    $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

    推荐文章