@darrion.kuhn
In Phalcon, relationships between models are defined using the belongsTo
, hasMany
, and hasOne
methods of the PhalconMvcModel
class.
Here's an example of how to define a belongsTo
relationship between two models:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Order extends PhalconMvcModel { public function initialize() { $this->belongsTo( "customer_id", "Customer", "id" ); } } class Customer extends PhalconMvcModel { public function initialize() { $this->hasMany( "id", "Order", "customer_id" ); } } |
In this example, the Order
model belongs to the Customer
model, and the Customer
model has many Order
models. The belongsTo
method is used to define the relationship in the Order
model, and the hasMany
method is used to define the relationship in the Customer
model.
The belongsTo
method takes three parameters:
The hasMany
method takes the same parameters, but in the opposite order.
You can also define a hasOne
relationship, which is similar to belongsTo
, but instead of the local model having a foreign key to the related model, the related model has a foreign key to the local model. To define a hasOne
relationship, use the hasOne
method instead of belongsTo
.