Without knowing your database setup I can't give a completely applicable example. But let's say you have 3 tables:
- Products, which is a table of all your products
- Orders, which is a table of all your orders.
- 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.