Eager loading with resful in Yii 2

I’m using Restful API in Yii2. ( yii\rest\ActiveController )

Is there the way to use eager loading with it?

I tried this way.

/localhost/users?fields=id,email&expand=profile

But a lot of queries excuted and I think this is not better for performance, isn’t it?

Like this:




SELECT * FROM `profile` WHERE `id`=20

SELECT * FROM `profile` WHERE `id`=21

SELECT * FROM `profile` WHERE `id`=22

SELECT * FROM `profile` WHERE `id`=23

SELECT * FROM `profile` WHERE `id`=24

SELECT * FROM `profile` WHERE `id`=25

             :

             :

             :



I want it to excute with eager loading.

How do I do that?

Thanks.

Eager and Lazy loading depends on how you retrieve the data

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-and-eager-loading

You didn’t provide any useful info,


 /localhost/users?fields=id,email&expand=profile

is the way you call the url not the way you use the model.

Choosing between eager and lazy loading is matter of performance vs memory saving.

Anyway if you want to use eager loading you should do something like this:


$customers = User::find()->with('Profile')->all();

I think yii\rest\ActiveController is mostly useful for fast prototyping where perfomance has minor importance. For production code you might have to implement custom actions with the necessary optimizations and application-specific logic.