What is going on with me on Yii model Relation ! I have 2 Models:
`Question and Video`,
I am saving
`question_id` in `Video model as foreign key`,
Now I want to build a relation in Question model
like this:
'video'=>array(self::HAS_MANY, 'Video', '', 'on'=>'video.question_id=id'),
and then in clistview I am showing :
if (!empty($data->video))
echo CHtml::encode($data->video->video_title);
but nothing happen there, what's wrong with my code?
You have your relation setup incorrectly:
'video'=>array(self::HAS_MANY, 'Video', 'question_id'),
//this compares Video->question_id to Question->primary_key
You don't need to specify on
, it uses the third criteria question_id
and compares it to the primary key of your Question model since you are specifying HAS_MANY
. If you had a relation of BELONGS_TO
the third criteria refers to the attribute in that model and compares it to the foreign key in the other model. So if you had the opposite relationship setup on your Video
model it would be:
'question'=>array(self::BELONGS_TO,'Question','question_id'),
//this compares Video->question_id to Question->primary_key
Also you currently have
echo CHtml::encode($data->video->video_title);
Since you are specifying that it HAS_MANY
$data->video
will be an array of Video instances. So you have two options just use the first element in the array data->video[0]->video_title
or convert HAS_MANY
into HAS_ONE
then it will only make one connection and not look for multiples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.