@this__all

Как переделать запрос mysql в Yii код?

Кто сможет помочь переделать запрос из mysql в Yii код

SELECT author.name as author, count(*) AS quantity
FROM book 
INNER JOIN author on book.id_author = author.id_author
GROUP BY author.id_author


Контроллер Book

<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Book;
use app\models\Author;

class SortController extends Controller {
  public function actionSort() {
    $years = Book::find()
      ->where('year>=1901')
      ->all();
      
    $query = "SELECT author.name as author, count(*) AS quantity
              FROM book 
              INNER JOIN author on book.id_author = author.id_author
              GROUP BY author.id_author";
    $books = Author::findBySql($query)->all();

    return $this->render('sort', [
      'years' => $years,
      'books' => $books,
    ]);
  }
}


Модель Author

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Author extends ActiveRecord {
  public function getGenre() {
    return $this->hasOne(Genre::className(), ['id_genre' => 'id_genre']);
  }

  public function getBooks() {
    return $this->hasMany(Book::className(), ['id_author' => 'id_author']);
  }
}


Модель Book

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Book extends ActiveRecord {
  public function getAuthors() {
    return $this->hasOne(Author::className(), ['id_genre' => 'id_genre']);
  }
}

База Данных 

<img src="https://habrastorage.org/webt/5e/a6/ef/5ea6efddd8925155899839.jpeg" alt="image"/>
  • Вопрос задан
  • 62 просмотра
Пригласить эксперта
Ответы на вопрос 1
@this__all Автор вопроса
У меня получилось вот так

<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Book;
use app\models\Author;

class SortController extends Controller {
  public function actionSort() {
    $years = Book::find()
      ->where('year>=1901')
      ->all();
      
    $books = Book::find()->all();

    $books = $books->select('author.name as author, COUNT(*) AS quantity')
      ->form('book')
      ->joinWith('author on book.id_author = author.id_author')
      ->groupBy('author.id_author');

    var_dump($books);

    return $this->render('sort', [
      'years' => $years,
      'books' => $books,
    ]);
  }
}


Но выдаёт ошибку "all to a member function select() on array" вот в этой строчки

$books = $books->select('author.name as author, COUNT(*) AS quantity')
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы