首页 > 解决方案 > Cakephp 如何映射和合并两个对象?

问题描述

我有两个对象coinsuser_summarry

$coins = $this->coins->find('all')

$user_summarry = $this->UserSummary->find('all')

如果我toArray()用于硬币,它看起来像

[
   (int) 0 => object(App\Model\Entity\Coin) id:0 {
      'id' => (int) 1
      'name' => 'A'
    }
    (int) 1 => object(App\Model\Entity\Coin) id:0 {
      'id' => (int) 2
      'name' => 'B'
    }
  ....
]

toArray()为了user_summarry

[
   (int) 0 => object(App\Model\Entity\UserSummary) id:0 {
        'id' => (int) 1
        'coin_id' => '2'
        'total' => 120

   }
   ...
]

我怎样才能改变我的硬币对象

(int) 0 => object(App\Model\Entity\Coin) id:0 {
      'id' => (int) 1
      'name' => 'A',
      'total' => 0
}
(int) 1 => object(App\Model\Entity\Coin) id:0 {
      'id' => (int) 2
      'name' => 'B',
      'total' => 120

}

通过使用 2 foreach 循环更改数组后,我可以将其更改为数组。如何使用 cakephp 方法映射和连接为对象?

标签: cakephpcakephp-4.x

解决方案


小建议:

硬币表:

$this->hasOne('UserSummary',[
   'foreignKey' => 'UserSummary.coin_id',
];

在您的控制器中:

$results = $this->Coins->find()
   ->select(['id' => 'Coins.id', 'name' => 'Coins.name', 'total' => 'UserSummary.total'])
   ->toArray();

debug($results);

推荐阅读