E
E
ewolf2015-05-14 13:51:36
Yii
ewolf, 2015-05-14 13:51:36

How to make links in Yii2 between two models in different modules?

Good afternoon everyone.
Suppose there is some extension for Yii2, for example, a directory that has an Orders model, which in turn I want to associate with the Users model. Base structure example:

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL
)

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
)

And respectively two models:
class Order 
{

}

class User
{

}

I want to add a relation to User to the Order model, like this:
...
public function getUser() 
{
    return $this->hasOne(User::className(), ['id' => 'user_id'];
}
...

but here in this place there is one important feature: the Order and User models (and, accordingly, the tables created using migrations) are in different modules / extensions. Moreover, the module for users can be replaced by another one (for example, in another project).
Accordingly, I cannot simply reference User::className(), because the class name and its namespace may be different.
Thus, the question is: how to specify in the getUser method a reference to the User class that will correspond to the current project?
My Options
  1. In the module properties for Order, add the $userClass property and write the class name there
  2. Redefine the Order class in some place (for example, in the Bootstrap application) using the child class and already in this child set the relation, for example:
    class OrderWithUser extends Order {
        public function getUser() 
        {
            return $this->hasOne(User::className(), ['id' => 'user_id'];
        }
    }
    
    // В bootstrap
    Yii::$container->set('namespace/to/Order', 'namespace/to/subclass/OrderWithUser')

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Grechushnikov, 2015-05-14
@ewolf

return $this->hasOne(\app\module\admin\models\User::className(), ['id' => 'user_id'];
what's stopping you from doing this?

E
ewolf, 2015-05-14
@ewolf

It interferes with the fact that the \app\module\admin\models\User model can be replaced with another one, in another module with a different namespace. The only thing that models can have in common is that they:
a. Both are inherited from ActiveRecord
b. They can have some common interface (for example, UserInterface), which will describe the methods that are mandatory for all of them (for example, getFullName, etc.).

T
Terminaft, 2015-05-14
@Terminaft

Store the user class in the parameters, and from there drag it to getUser

R
Roman Zhuravlev, 2015-05-14
@Zhuravljov

Use \yii\web\User::$identityClass
That is, in the module model your link will look like this:

public function getUser()
{
    return $this->hasOne(Yii::$app->user->identityClass, ['id' => 'user_id']);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question