没有不值得去解决的问题,也没有不值得去学习的技术!

Analyzing and Resolving String Response Field Types When Querying Data With yii\db\ActiveQuery::joinWith() Relationship Declarations in Yii 2

The actual response result is as follows: all field types are strings

1. In \qq\rests\article_category\StandardIndexAction.php

PHP

	/* @var $modelClass \yii\db\BaseActiveRecord */
	$modelClass = $this->modelClass;

	$query = $modelClass::find()
		->joinWith('qqArticleCategoryNormal')
		->where([
			$modelClass::tableName() . '.is_deleted' => $modelClass::IS_DELETED_NO,
			QqArticleCategoryNormal::tableName() . '.is_deleted' => QqArticleCategoryNormal::IS_DELETED_NO,
		])
		->asArray()
		->orderBy([$modelClass::tableName() . '.id' => SORT_DESC]);
	if (!empty($filter)) {
		$query->andFilterWhere($filter);
	}

	// 设置每页资源数量默认为资源总数
	$count = (int) $query->count($modelClass::tableName() . '.id');
	if (empty($requestParams['per-page'])) {
		$requestParams['per-page'] = $count;
	}

	return Yii::createObject([
		'class' => ActiveDataProvider::className(),
		'query' => $query,
		'pagination' => [
			'params' => $requestParams,
			'pageSizeLimit' => [1, $count],
		],
		'sort' => [
			'params' => $requestParams,
		],
	]);

2. The expected response result is as follows:

JSON

	"items": [
		{
			"id": 226,
			"name": "其他综艺",
			"parent_id": 0,
			"status": 1,
			"is_deleted": 0,
			"created_at": 1542178227,
			"updated_at": 1542178227,
			"deleted_at": 0
		},
		{
			"id": 225,
			"name": "舞台剧",
			"parent_id": 0,
			"status": 1,
			"is_deleted": 0,
			"created_at": 1542178227,
			"updated_at": 1542178227,
			"deleted_at": 0
		}
	]

3. The actual response result is as follows: all field types are strings, as shown in Figure 1

The actual response result is as follows: all field types are strings
Figure 1
JSON

	"items": [
		{
			"id": "67",
			"name": "跑步",
			"parent_id": "0",
			"status": "1",
			"is_deleted": "0",
			"created_at": "1542178227",
			"updated_at": "1542178227",
			"deleted_at": "0"
		},
		{
			"id": "66",
			"name": "健身",
			"parent_id": "0",
			"status": "1",
			"is_deleted": "0",
			"created_at": "1542178227",
			"updated_at": "1542178227",
			"deleted_at": "0"
		}
	]


4. Edit \qq\rests\article_category\Serializer.php to print $models

PHP

class Serializer extends \yii\rest\Serializer
{
    /**
     * Serializes a data provider.
     * @param DataProviderInterface $dataProvider
     * @return array the array representation of the data provider.
     */
    protected function serializeDataProvider($dataProvider)
    {
        if ($this->preserveKeys) {
            $models = $dataProvider->getModels();
        } else {
            $models = array_values($dataProvider->getModels());
        }
        $models = $this->serializeModels($models);

        var_dump($models);
        exit;
	}
}

5. The print result is as follows, all fields are strings

Plaintext
array(67) {
  [0]=>
  array(9) {
    ["id"]=>
    string(2) "67"
    ["name"]=>
    string(6) "跑步"
    ["parent_id"]=>
    string(1) "0"
    ["status"]=>
    string(1) "1"
    ["is_deleted"]=>
    string(1) "0"
    ["created_at"]=>
    string(10) "1542178227"
    ["updated_at"]=>
    string(10) "1542178227"
    ["deleted_at"]=>
    string(1) "0"
    ["qqArticleCategoryNormal"]=>
    array(8) {
      ["id"]=>
      string(3) "334"
      ["article_category_id"]=>
      string(2) "67"
      ["name"]=>
      string(6) "跑步"
      ["status"]=>
      string(1) "1"
      ["is_deleted"]=>
      string(1) "0"
      ["created_at"]=>
      string(10) "1542178227"
      ["updated_at"]=>
      string(10) "1542178227"
      ["deleted_at"]=>
      string(1) "0"
    }
  }
}

6. Edit \qq\rests\article_category\StandardIndexAction.php and remove ->asArray(), because only the current model’s data is needed, not the related model’s data (i.e., qqArticleCategoryNormal)

PHP

        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        $query = $modelClass::find()
            ->joinWith('qqArticleCategoryNormal')
            ->where([
                $modelClass::tableName() . '.is_deleted' => $modelClass::IS_DELETED_NO,
                QqArticleCategoryNormal::tableName() . '.is_deleted' => QqArticleCategoryNormal::IS_DELETED_NO,
            ])
            ->orderBy([$modelClass::tableName() . '.id' => SORT_DESC]);
        if (!empty($filter)) {
            $query->andFilterWhere($filter);
        }

        // 设置每页资源数量默认为资源总数
        $count = (int) $query->count($modelClass::tableName() . '.id');
        if (empty($requestParams['per-page'])) {
            $requestParams['per-page'] = $count;
        }

        return Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
                'pageSizeLimit' => [1, $count],
            ],
            'sort' => [
                'params' => $requestParams,
            ],
        ]);

7. The actual response result is as follows: the field types are consistent with those in the database, meeting expectations, as shown in Figure 2

The actual response result is as follows: the field types are consistent with those in the database, meeting expectations
Figure 2
JSON

	"items": [
		{
			"id": 67,
			"name": "跑步",
			"parent_id": 0,
			"status": 1,
			"is_deleted": 0,
			"created_at": 1542178227,
			"updated_at": 1542178227,
			"deleted_at": 0
		},
		{
			"id": 66,
			"name": "健身",
			"parent_id": 0,
			"status": 1,
			"is_deleted": 0,
			"created_at": 1542178227,
			"updated_at": 1542178227,
			"deleted_at": 0
		}
	]

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系