Answer the question
In order to leave comments, you need to log in
Yii2 How to display data from one table if there is at least one match in another?
There are two tables
1. categories (id, name, bla, bla, bla)
2. posts (id, text, category_id)
In the posts table , the category_id field has a foreign key that is associated with the categories.id
field
This is what I want to ask the server in English:
I want to get all entries from categories for which there is at least one entry in posts.
Those. I only need those categories that have posts. It may be an idiotic question, but my head is already thinking badly in the evening. Tell me how to get them out?
Answer the question
In order to leave comments, you need to log in
There is a join for this, an example:
$customers = Customer::find()
->select([
'{{customer}}.*', // получить все атрибуты покупателя
'COUNT({{order}}.id) AS ordersCount' // вычислить количество заказов
])
->joinWith('orders') // обеспечить построение промежуточной таблицы
->groupBy('{{customer}}.id') // сгруппировать результаты, чтобы заставить агрегацию работать
->all();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question