AR - avoid multiple instances for single DB record

Hi all,

I’m searching for a solution that always provides me with the same ActiveRecord instance when querying for a record that has already been loaded. To make things clear, imagine the following example:




$userComments = $user->ownComments;

$articleComments = $article->comments;



Now, chances are that $user has commented $article, so we’d get two Comment instances representing the same database record. In my case, I’m working on the loaded instances and need to save them. And I want to avoid them overriding each other.

Can anyone think of a solution for this problem?

That’s called “entity map”. Not supported out of the box because it has its cons as well as pros.

I see. Can you think of a way to build something like this on top of the AR implementation? Or maybe more like injecting some sort of loader into the AR implementation? Because the only way I can imagine doing it would be to:

1 ) load a record

2 ) compare its PK to a collection of already loaded records

3.a ) populate AR if the record hasn’t been loaded before, or

3.b ) throw the record away, returning the already existing AR if it already has been loaded

Or do you think it might be a better choice to use another persistence solution, supporting the feature?

(doctrine seems like an alternative to me, although it might very well come with its own caveats I’m just not aware of yet.)

Your plan is OK.

  1. Is about overriding instantiate($row) method of your model.

Thanks for your help! I’ll give it a try.

Hi,

you can relate your models inside a single model. Like such a method to get data from two related models:


    public function getAllActiveProviderData()

    {

        $allActiveProviderData = $this->hasMany(ProviderData::className(), ['provider_id' => 'id'])

                                        ->where('active = 1')->all();

        return $allActiveProviderData;

    }