Skip to content

Proposal: Work with the related models in AR like one-entity. #69

Description

@asamats

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):

  1. 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']
  2. eager-loading isn't necessary

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions