【问题标题】:Cakephp how can I map and merge two object?Cakephp 如何映射和合并两个对象?
【发布时间】:2021-08-03 07:54:55
【问题描述】:

我有两个对象 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 方法映射和连接为对象?

【问题讨论】:

    标签: cakephp cakephp-4.x


    【解决方案1】:

    快速提示:

    硬币表:

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

    在您的控制器中:

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

    【讨论】:

    • 我在这里举了一个例子,在我的情况下,我必须在对象匹配中做到这一点。
    • @NiloyRony 您给出的示例不保证 PHP 级别的合并,因此它吸引了这样的答案(这在技术上是正确的)。您可能想用一个概述在 PHP 级别合并的技术必要性的示例来更新您的问题,或者只是将其与合并数组/集合的一般任务有关。
    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多