I have 3 tables: sp_pages
, sp_messages
and sp_messages_pages
(for many-to-many relations).
The sp_messages_pages
table have 5 columns:
- id
- page_id
- message_id
- enabled
- sorting_order
I want to get all messages for specific page sorting by sp_messages_pages.sorting_order
using Yii2 framework.
I try this code in pages
class:
public function getMessages() {
return $this->hasMany(Messages::className(), ['id' => 'id_messages'])
->viaTable('sp_messages_pages', ['id_pages' => 'id'], function ($query) {
$query->andWhere(['enabled' => 'Yes'])
->orderBy(['sp_messages_pages.sorting' => SORT_ASC]);
});
}
I use this code in my controller:
$this->findModel(['slug' => $slug])->getMessages();
This give me all messages sorted by sp_message.id
. The generated SQL is
SELECT * FROM
sp_messages
WHEREid
IN ('2', '3', '1', '4', '5')
IN
condition is sorted as I want, but how to sort sp_messages
?
First way -- joining relation table to already selected
messages
almost the the same question here: Yii2 order items of many-to-many relation
Other way -- using findBySql
but this is will be not a relation in Yii therms, just an method which returns
ActiveQuery
for further work. You can use such method as$page->getMessages()->all()
for example.