How to get the value linked to a foregin key


(Ludm) #1

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


(Mattia Minini) #2

$model->author->name

getAuthor() return the ActiveQuery Object


(Ludm) #3

Thank you, it works :wink: