Reputation: 67
I have model material has one to one relation with table data
When I call
$material = \app\models\Material::find()->where(['material.id'=> 417974])->with('data')->one();
and the try to get $material->data->title it gives queries.
When try use joinWith
$material = \app\models\Material::find()->select('"material".*, "data".*')->where(['material.id'=> 417974])->joinWith('data')->one();
and in SQL query I get all columns from 2 tables, but $material->data->title still adds extra query
Upvotes: 1
Views: 603
Reputation: 6144
You can't really force Yii to load model and it's related model in same query. Even if your relation is one to one Yii will load related model in separate query.
$material = \app\models\Material::find()
->where(['material.id'=> 417974])
->with('data')
->one();
Using eager loading like this, will cause Yii to load related model during that one()
method call but it will still use separate query to load related model's data.
If you want to load all data in single query, you will need to load them as array instead of loading them into model:
$material = \app\models\Material::find()
->select('material.*, data.*')
->where(['material.id'=> 417974])
->joinWith('data')
->asArray()
->one();
If you really insist in loading data in single query and getting it as model you can instantiate/populate the model and its relation yourself.
$row = \app\models\Material::find()
->select('material.*, data.*')
->where(['material.id'=> 417974])
->joinWith('data')
->asArray()
->one();
// Create instance of Material model
$material = \app\models\Material::instantiate($row);
// Populate Material model instance with loaded data
\app\models\Material::populateRecord($material, $row);
// Assuming the related model class is \app\models\Data
// Create instance of related Data model
$data = \app\models\Data::instantiate($row);
// Populate Data model instance with loaded data
\app\models\Data::populateRecord($data, $row);
// Populate data relation in Material model instance
$material->populateRelation('data', $data);
But honestly, in most cases it's better to just let the framework do its job. Unless the query for loading related model is really slow the performance improvement from removing that single query will be minimal and your code will get cluttered with loading logic.
Upvotes: 2