Using ActiveDataProvider, how can I sort by related column with condition

I have two tables, alpha and beta, how can I sort alpha.id by beta.content that has beta.gamma_id = ‘Meat’?

alpha

id

1

2

beta

id | alpha_id | gamma_id | content


1 | 1 | Fruit | D

2 | 1 | Meat | B

3 | 2 | Fruit | C

4 | 2 | Meat | A

I have found the answer. The key is to use mysql having.

This is what I added to AlphaSearch.php at the end of the search() function:

$query->select([‘alpha*’, ‘beta.gamma_id’, ‘beta.content’]);

$query->andHaving('beta.gamma_id = Meat');

$query->orderBy([

‘beta.content’ => SORT_DESC

]);