Answer the question
In order to leave comments, you need to log in
What pattern to use for interaction from one place depending on the config (YII2)?
Tell me which pattern to use. The task is this. There is an Orders entity. But orders can be both for sale and for purchase. These properties are stored in different tables, only three tables are Orders, purchase data, sales data. It turns out that when we want to display our order, we create the order model and then, depending on the type, pull up the data. Thus, we can create a universal way to display data in a view. Where, depending on the type, we use this or that method, referring to this or that table ....
now it looks like this
class Order extends ActiveRecord {
const TYPE_SELL = 1;
const TYPE_BUY = 2;
private $_params = null;
private function setParams() {
$this->_params = array();
if ($this->type == self::TYPE_BUY) {
//$Source = Order_requests::find()->where( ['id' => $this->source_id] )->one();
} else {
$Source = Certificate::find()->where( ['id' => $this->source_id] )->one();
}
foreach ($Source as $key => $val) {
$this->_params[$key] = $val; //get data from certificate model by source_id
}
}
function getParam($key) {
if (is_null($this->_params)) {
$this->setParams();
}
return isset($this->_params[$key]) ? $this->_params[$key] : null;
}
/**
* @inheritdoc
*/
public static function tableName() {
return '{{%orders}}';
}
Answer the question
In order to leave comments, you need to log in
I didn’t delve into your code much, but read this article about different tables for identical, slightly different models, maybe you are reinventing the wheel.
you need to do it like this:
3 models 3 tables
order model with type parameter and general data
model for type 1
model for type 2
in the order model connection dependent on the type parameter, for example:
publiс function getData(){
switch($this->type){
case 1:
$data = $this->hasMany(Model1::classname(),['order_id'=>'id']);
break;
case 2:
$data = $this->hasMany(Model2::classname(),['order_id'=>'id']);
break;
default:
$data = null;
}
return $data;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question