Answer the question
In order to leave comments, you need to log in
How to set up relationships between models in Yii2?
The task is executed on Yii2. There are 2 models Book and Author, there are 2 tables in MySQL database book and author. The author stores the id and name of the author. In book, among other things, there is an author_id identifying the author of the book. Through the BookController in the View, all the necessary fields from the book table are displayed in a loop, but besides this, you also need to display the author's name. But since my knowledge of the matbase is below the plinth, I can’t do this. The documentation did not save, by analogy, it was not possible to do 100500 examples found, apparently I'm missing something.
book model:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Book extends ActiveRecord {
public static function tableName() {
return 'book';
}
}
<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\book;
use app\models\author;
class BookController extends Controller {
public function actionIndex() {
$book = Book::find()->select('image, title')->all();
$author = 'Тут будет имя автора';
return $this->render('index', compact('book', 'author'));
}
}
<div class="col-sm-12 col-md-12">
<?php if(!empty($book)); ?>
<?php foreach($book as $book): ?>
<div class="col-sm-6 col-md-3 row" style="margin: 20px auto 20px auto;">
<div class="thumbnail">
<img src="<?=$book->image?>" alt="...">
<div class="caption">
<h3><a href="#"> <?=$book->title?> </a></h3>
<p> <?=$author ?></p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
I provided links in my previous reply. Read carefully.
Let's represent the structure book:
id|name|author_id
and present the structure author:
id|name
Let's write two classes:
<?php
class Author extends ActiveRecord
{
public static function tableName()
{
return 'author';
}
pubic static function primaryKey()
{
return ['id'];
}
}
class Book extends ActiveRecord
{
public static function tableName()
{
return 'book';
}
public static function primaryKey()
{
return ['id'];
}
public function getAuthor()
{
return $this->hasOne(Author::className(), ['id' => 'author_id']);
}
}
// Использование:
$books = Book::find()->all();
foreach ($books as $book) {
echo $book->author->name; // сработает метод getAuthor() из Book
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question