R
R
remarkxaM2017-07-12 17:29:45
Yii
remarkxaM, 2017-07-12 17:29:45

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

2 answer(s)
M
Maxim Timofeev, 2017-07-12
@remarkxaM

There is a join for this, an example:

$customers = Customer::find()
    ->select([
        '{{customer}}.*', // получить все атрибуты покупателя
        'COUNT({{order}}.id) AS ordersCount' // вычислить количество заказов
    ])
    ->joinWith('orders') // обеспечить построение промежуточной таблицы
    ->groupBy('{{customer}}.id') // сгруппировать результаты, чтобы заставить агрегацию работать
    ->all();

Read here
Well, if the word join met in you for the first time in your life, then first read here

A
Alexander, 2017-07-12
@l1tero

Here is the answer. You are interested in the section about this and that. In short, put relations in the models and do join in the query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question