sty-wolf
Новичок
у меня есть три таблицы books, authors и объединяющая таблица authors_books, для наглядности привожу картинку

привожу метод для наглядности
как сделать чтоб авторы книг, сортировались ?

Код:
CREATE TABLE `authors` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Дамп данных таблицы `authors`
--
INSERT INTO `authors` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'author 1', 1564150918, 1564150918),
(2, 'author 2', 1564150918, 1564150918),
(3, 'author 3', 1564150918, 1564150918),
(4, 'Vladimir', 1564160781, 1564160781),
(5, 'vasy', 1564170027, 1564170027);
-- --------------------------------------------------------
--
-- Структура таблицы `authors_books`
--
CREATE TABLE `authors_books` (
`id` int(11) NOT NULL,
`author_id` int(11) NOT NULL,
`book_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `authors_books`
--
INSERT INTO `authors_books` (`id`, `author_id`, `book_id`) VALUES
(2, 2, 2),
(3, 3, 3),
(1, 4, 1);
-- --------------------------------------------------------
--
-- Структура таблицы `books`
--
CREATE TABLE `books` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Дамп данных таблицы `books`
--
INSERT INTO `books` (`id`, `name`, `created_at`, `updated_at`) VALUES
(1, 'my book', 1564160818, 1564160818),
(2, 'book2', 1564162666, 1564162666),
(3, 'book3', 1564162675, 1564162675);
Код:
public function search($params)
{
$query = Books::find()->with('authors');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes' => [
// 'id',
'name',
'created_at',
'updated_at',
'authorsName',
],
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'FROM_UNIXTIME({{%books}}.created_at, "%d-%m-%Y")' => $this->created_at,
'FROM_UNIXTIME({{%books}}.updated_at, "%d-%m-%Y")' => $this->updated_at,
]);
$query->andFilterWhere(['like', '{{%books}}.name', $this->name]);
$query->joinWith('authors')->andFilterWhere(['like', '{{%authors}}.name', $this->authorsName]);
return $dataProvider;
}
}