Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ol's avatar
Level 1

Where &Join

There is a problem in querying joined tables. Join three many-to-many tables. But each has an id column from the main table news,img_news, subregions. and a news table can have several sub-regions and several images. This request is certainly not correct. But as an example.

$news = DB::table('news')
            ->OrderBy('rating', 'DESC')
            ->where('region_id', '=', 1)
            ->join('img_news', 'news.id', '=', 'img_news.news_id')
            ->join('subregions', 'news.subregion_id', '=', 'news.id')
            ->select('news.*', 'img_news.img', 'subregions.name_subregion')
            ->get();

Rather, the problem is in the query, how to make a query to the main table news by region_id, get an array of IDs for these regions. And after that, get on the ID of the region, get their images and sub-regions. I have no thoughts left at all. Thank you for any idea and help !!!

0 likes
6 replies
MichalOravec's avatar
Level 75

Do you think a code what you posted above is readable?

$news = DB::table('news')->select('news.*', 'img_news.img', 'subregions.name_subregion')
    ->join('img_news', 'news.id', '=', 'img_news.news_id')
    ->join('subregions', 'news.subregion_id', '=', 'news.id')
    ->where('news.region_id', 1)
    ->orderByDesc('news.rating')
    ->get();
ol's avatar
Level 1

How should I escape the code for readability. Unfortunately, I could not determine this.

ol's avatar
Level 1

I fixed the display of the code. Thanks for the help !!! i test it

ol's avatar
Level 1

I get an empty answer. No mistake.

ol's avatar
Level 1

Everything works fine. Was my carelessness! Thanks again

Please or to participate in this conversation.