P
P
Paulus2015-08-19 22:52:35
Yii
Paulus, 2015-08-19 22:52:35

Is there a way in Yii2 to set an associated model without hasOne/hasMany?

Good afternoon.
Please tell me if there is a way in Yii2 to set the associated model not through an explicit method (getCar), but through a class property. Something along the lines of:

class Driver extends ActiveRecord
{
    public $car;

    public function init() 
    {
          $this->car = Car::findOne($this->carId);
          parent::init();
     }
}

The goal is to collect the relationship declaration in a single model method.
The example above does not set the car property because the carId property has not yet been populated with data from the database at the time the init() method is executed.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Klyuev, 2015-08-20
@ppokrovsky

Your goal is strange.
Why collect everything in the 1st method? Well, if necessary, you can compile it (see above), but here's how your code will work after this assembly... Moreover, you have a lot of links, since you want to collect THEM in one place ..
What are the disadvantages of your Wishlist:
1 You will not be able to download the 1st request and the driver and auto, ie. the number of queries to the database is increased by 2 times;
2. You won't be able to use a relationship in queries (you just won't have it), which means that in slightly more complex queries you will have to join everything yourself.
3. Yes, you can think of a bunch of minuses ...
If you want to collect all the declarations of links in one place, well, collect them (the methods that define the links themselves) in one place in the model code and it will immediately be clearly visible what a particular model is connected to. In general, I advise you to develop for yourself a "template" for building a model, so that the order of the order of methods is in different 1-in models, for example ...

Q
QuickStudio, 2015-08-20
@QuickStudio

I don’t understand one thing - why not do it through the connection and use eagerLoad?
If you already want such perversions - use event - self::AFTER_FIND

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question