【问题标题】:How to avoid _matchingData and get a specific value instead如何避免 _matchingData 并改为获取特定值
【发布时间】:2021-07-15 14:01:54
【问题描述】:

在订单表模型中,我需要与订单关联的产品的类别 ID

模型/表格/OrdersTable.php

    public function updateQuantityForInventoryItems(array $orders_items): void
    {
        $ordersItemsIds = [];

        foreach ($orders_items as $orders_item) {
            array_push($ordersItemsIds, $orders_item->product_id);
        }

        $catIds = $this->find('ordersItemsCategories', ['ordersItemsIds' => $ordersItemsIds])->toArray();

        dd($catIds);

        $InventoriesTable = TableRegistry::getTableLocator()->get('Inventories');
        $InventoriesTable->updateQuantityForInventoryItems('orders', $catIds);
    }

    public function findOrdersItemsCategories(Query $query, array $options): Query
    {
        $query = $this->OrdersItems->Products
            ->find()
            ->select(['Products.id','CategoriesProducts.category_id'])
            ->matching(
                'CategoriesProducts', function (Query $q) use ($options) {
                return $q->where([
                    'CategoriesProducts.product_id IN' => $options['ordersItemsIds'],
                ]);
            });

        return $query->hydrate(false);
    }

生成的 SQL 查询

SELECT Products.id AS `Products__id`, CategoriesProducts.category_id AS `CategoriesProducts__category_id` FROM products Products INNER JOIN categories_products CategoriesProducts ON (CategoriesProducts.product_id in (4325,3632) AND Products.id = (CategoriesProducts.product_id))

当我用 dd($catIds); 打印出数组时,我得到一个包含 _matchingData 的数组

array:4 [▼
  0 => array:2 [▼
    "id" => 3632
    "_matchingData" => array:1 [▼
      "CategoriesProducts" => array:1 [▼
        "category_id" => 10
      ]
    ]
  ]
  1 => ...
]

如何获取id下的category_id

(我已经检查了那个线程How to print _matchingData object value in cakephp 3但仍然没有成功)

【问题讨论】:

    标签: cakephp-3.0


    【解决方案1】:

    知道了。我需要给 category_id 起别名以防止嵌套

    ->select(['category_id' => 'CategoriesProducts.category_id'])
    

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2021-07-13
      • 2017-02-24
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 2012-12-09
      • 2011-05-03
      相关资源
      最近更新 更多