首页 > 解决方案 > 如何从 Yii2 中的 select() 访问值?

问题描述

如何访问从select(). 我想要所有链接表中的所有 id。我categoryMaster_id作为参数传递,因此我需要剩余的 id。

这是我到目前为止所做的:

$categoryMaster= (new \yii\db\Query())
    ->select('categoryMaster.categoryMaster_id,categoryMaster_name,categoryMaster_image,
    productType.productType_id,productType.productType_type,
    product.product_id,product.product_name,product.product_description,
    productQuantity.productQuantity_id,productQuantity.productQuantity_name,productQuantity.productQuantity')
    ->from('categoryMaster')
    ->join('LEFT JOIN','productType', 'productType.categoryMaster_id = categoryMaster.categoryMaster_id')
    ->join('LEFT JOIN','product','product.productType_id = productType.productType_id')
    ->join('LEFT JOIN','productQuantity','productQuantity.product_id = product.product_id')
    ->where('categoryMaster.categoryMaster_id=:categoryMaster_id', ['categoryMaster_id' => $_GET['categoryMaster_id']])
    ->all();   
    $data['categoryMaster']= $categoryMaster; 

标签: yii2

解决方案


如果您在选择中使用自定义列,您可能应该使用asArray()- 查询将结果作为数组而不是对象返回。

要从结果中提取指定的字段,您可以使用ArrayHelper::getColumn()

$result = (new \yii\db\Query())
    ->select('categoryMaster.categoryMaster_id,categoryMaster_name,categoryMaster_image,
        productType.productType_id,productType.productType_type,
        product.product_id,product.product_name,product.product_description,
        productQuantity.productQuantity_id,productQuantity.productQuantity_name,productQuantity.productQuantity')
    ->from('categoryMaster')
    ->join('LEFT JOIN','productType', 'productType.categoryMaster_id = categoryMaster.categoryMaster_id')
    ->join('LEFT JOIN','product','product.productType_id = productType.productType_id')
    ->join('LEFT JOIN','productQuantity','productQuantity.product_id = product.product_id')
    ->where('categoryMaster.categoryMaster_id=:categoryMaster_id', ['categoryMaster_id' => $_GET['categoryMaster_id']])
    ->asArray()
    ->all();  

$categoryMasterIds = ArrayHelper::getColumn($result, 'categoryMaster_id');
$productTypeIds = ArrayHelper::getColumn($result, 'productType_id');

或者使用闭包来提取 touple:

$productTypes = ArrayHelper::getColumn($result, function ($data) {
    return [
        'productType_id' => $data['productType_id'],
        'productType_type' => $data['productType_type'],
    ];
});

推荐阅读