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

Related model( automatic joins)

Hi there,

is it possible to execute a query like in Django, so it will make automatic joins ProductsOrders::findFirst("Order.User.id = product_id")

In that case ProductsOrders belongs to an Order and Order belongs to an order.

Thank you!

You have to use QueryBuilder check this docs

It might be simpler to set up the relationships in ProductsOrders->initialize() and Order->initialize(). Then you don't need to build special queries and can just refer to the related records automagically.



1.1k

Could you give an example?

It might be simpler to set up the relationships in ProductsOrders->initialize() and Order->initialize(). Then you don't need to build special queries and can just refer to the related records automagically.

Without knowing your database setup I can't give a completely applicable example. But let's say you have 3 tables:

  1. Products, which is a table of all your products
  2. Orders, which is a table of all your orders.
  3. ProductsOrders, which holds which products were in which orders.

So let's say you want to be able to know which Products were included in a particular Order. There are 2 ways you could set up relationships to do that.

First, you could set up simple relationships between all 3 tables:

class Orders{
    public function initialize(){
        $this->hasMany('id','ProductsOrders','order_id');
    }
}

class ProductsOrders{
    public function initialize(){
        $this->belongsTo('order_id','Orders','id');
        $this->hasOne('product_id','Products','id');
    }
}

class Products{
    public function initialize(){
        $this->belongsTo('id','ProductsOrders','product_id');
    }
}

With a given Order then, you could create a loop to iterate through all the products (for whatever reason):

$Order = Order::findFirst(39);//39 is just an example order id

foreach($Order->ProductsOrders as $ProductOrder){
    echo $ProductOrder->Product->name;
}

Another way you could set up the relations is just setting up 1 relation between Orders and Products, by way of ProductsOrders:

class Orders{
    public function initialize(){
        $this->hasManyToMany(
            'id',
            'ProductsOrders',
            'order_id','product_id',
            'Product',
            'id'
        );
    }
}

You could then iterate like so:

$Order = Order::findFirst(39);
foreach($Order->Product as $Product){
    echo $Product->name
}

I'd recommend looking through the documentation here: https://docs.phalcon.io/en/latest/db-models-relationships, as it goes through how to set up relationships. The documentation is quite thorough and helpful on this topic.