Need help with relations

Hey guys,

I’m new to Yii2 and right now I don’t get how I create relations between models. I have used Gii to generate a few models als also used the CRUD generator. I also tried setting foreign keys in the database - but Gii won’t generate the relations for me. But anyway this should also be possible manually right?

And at this point I need your help, let’s say I have the following classes “Product” and “Category”. The Product got a field “category” in which a category id will be saved. But how to I create the relationship so I have easy access to the category name instead of the category id (for example showing it in a GridView widget)?








<?php


namespace app\models;


use Yii;


/**

 * This is the model class for table "products".

 *

 * @property integer $id

 * @property string $name

 * @property string $description

 * @property double $price

 * @property integer $category

 */

class Product extends \yii\db\ActiveRecord {


  /**

   * @inheritdoc

   */

  public static function tableName() {

    return 'products';

  }


  /**

   * @inheritdoc

   */

  public function rules() {

    return [

       [['name', 'description', 'price', 'category'],'required'],

    ];

  }


  /**

   * @inheritdoc

   */

  public function attributeLabels() {

    return [

      'id' => 'ID',

      'name' => 'name',

      'description' => 'description',

      'price' => 'price',

      'category' => 'category',

    ];

  }


}













<?php


namespace app\models;


use Yii;


/**

 * This is the model class for table "categories".

 *

 * @property integer $id

 * @property string $description

 */

class Category extends \yii\db\ActiveRecord {


  /**

   * @inheritdoc

   */

  public static function tableName() {

    return 'categories';

  }


  /**

   * @inheritdoc

   */

  public function rules() {

    return [

      [['description'], 'required'],

      [['description'], 'string']

    ];

  }


  /**

   * @inheritdoc

   */

  public function attributeLabels() {

    return [

      'id' => 'ID',

      'description' => 'description',

    ];

  }


}




Thanks for helping me out! :)

Hello, the documentation has a very good section about how to work with database relations in the following link:

Active Records - Working with relational Data

Hi,

I would like to note that Gii can generate most of the relation declarations automatically. But for it to be able to do that, you need to specify Foreign Key Constraints in your DB first.

I got it solved, thank you guys!

Here’s a perfect example

https://www.tampaphp.com/articles/yii2/set-model-relationships