-
-
Notifications
You must be signed in to change notification settings - Fork 33
Description
I don't know how to name it, I just try to explain by example.
We have models like this:
class User extends ActiveRecord
{
// ...
public function getFiles(): ActiveQuery
{
return $this->hasMany(UserFile::class, ['id' => 'file_id']);
}
// ...
}
class UserFile extends ActiveRecord
{
// ...
}
And we need to load/save/update/etc User and UserFiles in one transaction because we wanna has integrity DB.
What we do: https://www.yiiframework.com/doc/guide/2.0/en/input-multiple-models
But it is not a right way to save/update integrity models.
Yes, we can use AR/DB transaction methods from Yii but I think must work by default when we work with related models/data.
And also we type same code for save related models.
My proposal:
When we wanna create/update/save/delete related models we must use eager-loading for get models:
User::find()-> with(['files'])->one();
... forms and etc.
And when we get data by request from browser we just use load function:
$user->load(Yii::$app->request->post())
And this function load all related models if it was loaded. And after that - validate & save all models like one Entity.
BUT: For security reason we must allow to work like this only for one "Entity".
What I mean - UserFiles without User doesn't have any value, User and UserFiles - it is one Entity. And for this we must have agreement that - If a model name has parent name (UserFiles has User) it must interpreted like one-single entity.
Thanks. I will be grateful for the reasoned criticism and additions.
And yes, I'm ready to implement this if it was be accepted.
UPDATE (2019-05-22):
- dependent models by model name (User -> [User]File) - reject
My proposal - use static method that return array where key is relation name and value is FQCN for dependent model
Example ['files' => 'app/models/UserFile'] - eager-loading isn't necessary