Yii模型阵列? [英] Yii model to array?

查看:21
本文介绍了Yii模型阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Trips::model()->findAll() 的结果转换为数组?

How can I convert the result of Trips::model()->findAll() to an array?

推荐答案

我在这里假设您只需要检索裸数组,而不需要检索任何关联的模型对象.

I'm going on the assumption here that you only need to retrieve just the bare arrays, and not any associated model objects.

这样做:

$model = Trips::model();
$trips = $model->getCommandBuilder()
               ->createFindCommand($model->tableSchema, $model->dbCriteria)
               ->queryAll();

这类似于 Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll(); 示例,除了:

This is like the Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll(); examples, except:

  • 它会向模型询问表名;您无需在模型和查询中都写入表名.

  • It'll ask the model for the table name; you won't need to write the table name in both the model and the query.

你可以在范围函数>$model 首先,例如
$model = Trips::model()->short()->destination('Austin, TX');
这样做意味着您可以使用模型现有的查询快捷方式,而不是直接将它们放入查询中.

You can call scoping functions on $model first, eg.
$model = Trips::model()->short()->destination('Austin, TX');
Doing this means you can use the model's existing query shortcuts, instead of putting them in the query directly.

相比之下,$trips = Trips::model()->findAll();(使用 foreach)有点浪费,因为您从数据库中提取行,设置一堆对象,然后将它们全部扔掉.它适用于小型结果集,但如果您正在查看一长串旅行,我不会使用它.

In contrast, the $trips = Trips::model()->findAll(); (using foreach) is a bit wasteful, in that you're pulling the rows from the database, setting up a bunch of objects, and then throwing them all away. It'll work fine for small result sets, but I wouldn't use that if you're looking at a long list of Trips.

警告:
不过,如果这只是一个快速原型,请务必使用 createCommand() 或 findAll()-and-loop 示例.

Caveat:
If this is just a quick prototype, though, by all means use the createCommand() or findAll()-and-loop examples.

这篇关于Yii模型阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆