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

Working with models (ORM) finding records

Hello everyone! I'm making a little web app with this awesome framework, is my very first time with one framework, so I'm a bit confused about some concepts...

I have a question about working with model and the ORM concept itself.

Let's say the I have a table called robots which has an id (PK) and name. Also I have a robot_parts which contains and id (its PK), robot_id (FK) and part_name.

How can I to magically use the ORM here?

Using models like $robots = Robots::findFirst(3); I can get the name with $robots->name, but how can I get the RobotParts->name?

Will $robots->RobotParts->part_name works? if not, is possible to achieve this behaviour? I know that I can use ORM to delete and save, but what about finding?

Thanks and please forgive my bad english.



13.9k
Accepted
answer

I found the way!

$robots->RobotParts[0]->part_name

edited Dec '17

Some explanation :)

$robots = Robots::findFirst(3); - this will return 1 object

$robots->RobotParts - this will return array of N related objects. So either you have to Iterate (foreach) over the robotParts or access as array like you did :)



13.9k

Thanks for explanation, it is really appreciated! I need to understand well that concept to make a use in things like this (not solved at the moment): https://forum.phalcon.io/discussion/17473/autocomplete-forms-using-orm-and-phalcon-forms

Could you take a look? Please.

Some explanation :)

$robots = Robots::findFirst(3); - this will return 1 object

$robots->RobotParts - this will return array of N related objects. So either you have to Iterate (foreach) over the robotParts or access as array like you did :)