Answer the question
In order to leave comments, you need to log in
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,
)
class Order
{
}
class User
{
}
...
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id'];
}
...
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
return $this->hasOne(\app\module\admin\models\User::className(), ['id' => 'user_id'];
what's stopping you from doing this?
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.).
Store the user class in the parameters, and from there drag it to getUser
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 questionAsk a Question
731 491 924 answers to any question