'Is it possible to make a polymorphic relationship in Yii2?
There are 4 tables - it can be simplified as follows (PostgresQL database)
CREATE TABLE PRODUCTS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
TYPE_PRODUCT INT NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE FOODS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
STATUS VARCHAR (50)
PRIMARY KEY (ID)
);
CREATE TABLE CLOTHES (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
STATUS VARCHAR (50)
PRIMARY KEY (ID)
);
CREATE TABLE CLEANERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
STATUS VARCHAR (50)
PRIMARY KEY (ID)
);
The meaning is this - the goods arrive at the warehouse and are registered in the first table. After acceptance and registration, the manager sends the goods, depending on the type, to the departments - Food, Clothing, Cleaning products. A product record is created in the corresponding table. That is, it is copied from the first table. Here I presented it in a simplified way, in fact, there are a lot of fields in the tables and there are different fields in each department. Therefore, apparently such a structure was made. But there is a status field in these tables. Is it possible to make it possible to display the calculated STATUS field from 2, 3, 4 tables when displaying a list of goods from the first main table.
I'm thinking of adding the EXTERNAL_ID field to the main table (where to write the id from the table where the record was copied) and using a polymorphic relationship (depending on TYPE_PRODUCT) pull out this Status field.
How can this be done in Yii2? On Laravel, this is easy to do - there are built-in tools. You only need to pull out this field when displaying the list (sorting) - no restrictions are required. This field will not be changed from the main table
I accept that all this could be put into one table or the status field could be made into the main table. But there is a problem with access rights. Managers in departments can neither view nor edit the master table. All this has been used for a very long time and no one will allow much change in the structure. You can only add a field to the main table
Solution 1:[1]
It is possible and really easy to implement.
Since you have your Product model you can define in it a relations that calls that specific model.
Product:
...
//Function to get a status of the Foods
public function getFoods()
{
return $this->hasOne(Foods::className(), ['foods_id' => 'id']);
}
//And so on on the rest of the tables
Now when you get your product in the table you can do as simple as that:
//$product Product model
$product->foods->status // It will return your food status.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serghei Leonenco |
