On the Yii2 framework, you need to implement your component, which takes several parameters and stores them in the database. How to implement it? (Problem, I don't know how to use activeRecord in this situation)

My model:

class Articles extends ActiveRecord { public static function tableName() { return 'med_articles'; } public function getCategory() { return $this->hasOne(Category::className(), ['cat_id' => 'cat_id']); } } 
  • and how do you use it in another situation? Do you even describe the model .. do you have it? What are the parameters? - Mikhail Rebrov
  • Model: class Articles extends ActiveRecord {public static function tableName () {return 'med_articles'; } public function getCategory () {return $ this-> hasOne (Category :: className (), ['cat_id' => 'cat_id']); }} The component method accepts parameters: the article title and description. It is necessary that the component, accepting the parameters, insert them into this table - Sergey
  • Read the Yii2 documentation, most of what you need is there. And about the fact that you do not know - write here, specific questions about specific problems. - Daniel Protopopov
  • @ Sergey, all this needs to be described in the question. How do you help people? - Mikhail Rebrov
  • I am quite new to this business) I will certainly take into account - Sergey

1 answer 1

It's simple. Create a component in the components folder. If you use the Advanced template, the path to the folder will be common/components , if the Basic template, create the components folder in the project root.

Code like this:

 <?php namespace [путь до папки components]; use [путь до модели]/Articles; class ArticleComponent extends \Yii\Base\Component { public function create($parametrOne, $parametrTwo) { $article = new Articles(); $article->parametr_one = $parametrOne; $article->parametr_two = $parametrTwo; return $article->save(); } } 

Next, in the site config we connect our component in the 'components' section 'components'

 'components' => [ ... 'article' => [ 'class' => '[namespace компонента]\ArticleComponent' ], ... ] 

Now you can use it anywhere on your site. For example, like this:

Yii::$app->article->create('parametr1', 'parametr2');