// 先执行sql: SELECT * FROM customer LIMIT 100;
// SELECT * FROM orders WHERE customer_id IN (1,2,...)
$customers = Customer::find()->limit(100)
->with('orders')->all();
foreach ($customers as $customer) {
// 在这个循环的时候就不会再执行sql了
$orders = $customer->orders;
// ...handle $orders...
}
照着文档里这么做,然后获取到的$orders是一个对象,如下:
yii\db\ActiveQuery Object
(
[sql] =>
[on] =>
[joinWith] =>
[select] =>
[selectOption] =>
[distinct] =>
[from] =>
[groupBy] =>
[join] =>
[having] =>
[union] =>
[params] => Array
(
)
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] => Array
(
)
[where] =>
[limit] =>
[offset] =>
[orderBy] =>
[indexBy] =>
[modelClass] => common\models\AuthAssignment
[with] =>
[asArray] =>
[multiple] =>
[primaryModel] => common\models\Admin Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 6
[username] => admin
[password_hash] => $2y$13$oYZrIQgTsipWdcNMKWCf8uxOIS286hOif9VWxf7.xnQ31MBje5AtS
[auth_key] => GQF9VeroKHrdo_72dzEF6SheBBOG-cuR
[status] => 1
[created_at] => 0
[last_time] => 1452569448
[ip] => 127.0.0.1
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 6
[username] => admin
[password_hash] => $2y$13$oYZrIQgTsipWdcNMKWCf8uxOIS286hOif9VWxf7.xnQ31MBje5AtS
[auth_key] => GQF9VeroKHrdo_72dzEF6SheBBOG-cuR
[status] => 1
[created_at] => 0
[last_time] => 1452569448
[ip] => 127.0.0.1
)
[_related:yii\db\BaseActiveRecord:private] => Array
(
[authitem] =>
)
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array
(
[beforeInsert] => Array
(
[0] => Array
(
[0] => Array
(
[0] => yii\behaviors\TimestampBehavior Object
(
[createdAtAttribute] => created_at
[updatedAtAttribute] => updated_at
[value] =>
[attributes] => Array
(
[beforeInsert] => Array
(
[0] => created_at
[1] => updated_at
)
[beforeUpdate] => updated_at
)
[owner] => common\models\Admin Object
*RECURSION*
)
[1] => evaluateAttributes
)
[1] =>
)
)
[beforeUpdate] => Array
(
[0] => Array
(
[0] => Array
(
[0] => yii\behaviors\TimestampBehavior Object
(
[createdAtAttribute] => created_at
[updatedAtAttribute] => updated_at
[value] =>
[attributes] => Array
(
[beforeInsert] => Array
(
[0] => created_at
[1] => updated_at
)
[beforeUpdate] => updated_at
)
[owner] => common\models\Admin Object
*RECURSION*
)
[1] => evaluateAttributes
)
[1] =>
)
)
)
[_behaviors:yii\base\Component:private] => Array
(
[0] => yii\behaviors\TimestampBehavior Object
(
[createdAtAttribute] => created_at
[updatedAtAttribute] => updated_at
[value] =>
[attributes] => Array
(
[beforeInsert] => Array
(
[0] => created_at
[1] => updated_at
)
[beforeUpdate] => updated_at
)
[owner] => common\models\Admin Object
*RECURSION*
)
)
)
[link] => Array
(
[item_name] => id
)
[via] =>
[inverseOf] =>
)
我要怎么处理这个对象,以获取我两个数据表数据的集合,初学者求教
$customers = Customer::find()->limit(100)
->with('orders')->**asArray()**->all();
楼上正解,加上asArray()返回的就是正常的数组了