We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Querys on multi tables

Hello,

Lets say I have 3 models Cars, CarsBrands and Brands.

Cars Model:


<?php

use Phalcon\Mvc\Model;

class Cars extends Model
{
    public $id;

    public $name;

    public $visits;

    public function initialize()
    {
        $this->hasMany('id', 'CarsBrands', 'car_id', ['alias' => 'cars_brands']);
    }
}

CarsBrands Model:


<?php

use Phalcon\Mvc\Model;

class CarsBrands extends Model
{
    public $id;

    public $brand_id;

    public $car_id;

    public function initialize()
    {
        $this->belongsTo('car_id', 'Cars', 'id');
        $this->belongsTo('brand_id', 'Brands', 'id');
    }
}

And brand model is not even importnat here.. It will have id and brand name ..

I need two querys.

I need to make query that will pull 10 cars from database ordered by visits number (visits is field n Cars), where brand id is not 5 (witouth cars with brand id 5).

Second query is, to pull 10 cars ordered by visits where brand id is 4.

Why have CarsBrands table at all? I mean can a single car have more than 1 brand? I don't think so. Why not just add brand_id column to Cars model?



23.5k

Why have CarsBrands table at all? I mean can a single car have more than 1 brand? I don't think so. Why not just add brand_id column to Cars model?

I know friend ... But this is just a example of the problem I have, not real situation :D That was a first question when I saw a models and database structure, but I cant change it ...

Don't have your exact table structure to test at the moment. But query should look like this:

SELECT
    N.id, N.created_at
FROM news_categories_relation AS R
LEFT JOIN news AS N ON N.id = R.news_id
WHERE R.news_category_id <> 3
GROUP BY N.id
ORDER BY N.id DESC