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

Basic hasMany->belongsTo relationship returns empty object

Hey All :) I've been doing a new project with MySQL instead of MongoDB since I need more relational capabilities.

I've seen the easy way Phalcon allows to configure relations and tried to add it.

There are two defined models:

Customers - Have an "id"

Checkins - Have an "id" and "customer" (which is the same as customer ID)

I'm connecting both with

// This is in "initialize()" in Customers.php Model
$this->hasMany("id", "Checkins", "customer"); 

// This is in "initialize()" in Checkins.php Model
$this->belongsTo("customer", "Customers", "id");

This seems pretty straightforward but when I fetch a customer and try to get his checkins I'm getting an empty object:

$c = Customers::findFirst();
$this->response->setJsonContent($c->checkins); // Returns empty object
return $this->response;

Needless to say, the "checkins" table has a checkin with a 'customer' field corresponding to an existing customer in the "customers" table.

Am I missing any steps? Maybe some special indexing is required?

Many thanks, Shai.

By the way, the interesting part is - when I do it the other way around it works flawlessly :

$c = Checkins::findFirst();

$this->response->setJsonContent($c->customers); // Returns the full customer object
return $this->response;


because its hasMany so it does not return an object if u do $c->checkins, but u can access it via $c->checkins[0] etc etc.. you have to provide an index =d

Wow, thanks 7thcubic.

That is truly odd... I expected "checkins" to be an array so I could see its entirety ... This doesn't seem like normal PHP behaviour ... How come $collection[0] gets output but $collection wouldn't ? ...


because the relationship is a hasMany, so it will return a container.

Oh ok, Just realised it returns an Iterator.

Thank you!