A model attribute is itself another model

I am using Yii2 . For my past three projects. The projects were small. But now I am using this for a mid level project. It’s a project where question set will be generated.

Every question has variable number of options and each question can have one or multiple correct answer.

Now I have created a Question model extending from Yii\base\model. And now my coding experience ( less than 4 years) expect a question model one of which atribute is ‘options’ which it self is a array of another model may be ‘option’ ActiverRecord model.

I don’t understand is this possible or not, if yes then how.

Or how this thing can be acheived in other way.

We usually do it like this:

  1. Create 2 database tables that represents "Question" and "Option".

1-1) ‘question’ table is like:

id … primary key

content … content of the question

1-2) ‘option’ table is like:

id … primary key

question_id … foreign key that points to a certain question

description … description of the option

1-3) establish a foreign key constraint between the 2 tables

Any row in the ‘option’ table must have the ‘question_id’ column that points to the ‘id’ column of an existing row of the ‘question’ table. By this constraint, any option must belong to one question, and any question can have multiple options. It’s a typical 1 to N relation.

  1. Create the corresponding ActiveRecord models from the db tables, usually using Gii’s model generator which is smart enough to analyse the relation between the tables. The created models will be like the following:

2-1) Question model has a "has many relation" called "options" which means that a question can have multiple options.

2-2) Option model has a "has one relation" called "question" which means that an option belongs to a certain question.

So, what you are trying to achieve by an attribute called "options" is usually implemented as a relation.

When you have retrieved an active record object of Question like the following:




$question = Question::findOne($id);



Then you can access its related options quite easily like this:




foreach ($question->options as $option) {

   echo $option->description;

}



The “options” relation is not an attribute. It’s initially a relational query object. But once you have accessed it, Yii will retrieve the contents from the database and replace it with an array of the related objects. So you can virtually use it as an attribute that contains the related objects. Yes, it’s quite convenient. :)

The whole concept is called "Relational Active Record."

Please look up the guide for more detailed information.Guide - Active Record And especially Working with Relational Data