Yii Framework Forum: How to get the value linked to a foregin key - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to get the value linked to a foregin key

#1 User is offline   Lu01 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 01-March 17

Posted 20 September 2017 - 10:10 AM

Hello,

I have a two models: Book and Author
Book:
id_book
title
fk_id_author


Author:
id_author
name


I would like to display the name of the Author when displaying a book

In the Book model I have a function to get the Author:
public function getAuthor(){
    return $this->hasOne(Author::className(), ['id_author' => 'fk_id_author']);
}


In my BookController I have
public function actionView($id){  return $this->render('view', [
     'model' => $this->findModel($id),
]);
}


In book/view.php I display the title of the book
echo $model->title;


How do I use the getAuthor() to display the name ?

I have tried
echo $model->getAuthor()->name;
and I got
Getting unknown property: yii\db\ActiveQuery::name

0

#2 User is offline   minitia 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 25
  • Joined: 19-December 12

Posted 20 September 2017 - 01:41 PM

$model->author->name

getAuthor() return the ActiveQuery Object
1

#3 User is offline   Lu01 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 01-March 17

Posted 20 September 2017 - 04:52 PM

Thank you, it works ;-)
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users