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

Assign FK to a Object - Is It a good Practice?

Hello I have a little question about relacional models 1:N and how can I assign the Foreign Key.

    public function CreateAction(){

        $id = 3;
        $part = Parts::findFirst($id); // Looking for my specific record (FK) to assign later

        $robot = new Robots();
        $robot->name = "Ironman";
        $robot->type = "5289756";
        $robot->id_parts = $part->id_parts; // Here is the Question - Is it a good practice?

        // $robots->id_parts = Local Column FK

        $robot->save(); //Save Data
    }

Really I don't know If I am following a good practice to assign FK to a Object (model) or no?

Do exist other ways?

Thanks!



33.8k

I should assign the robot_id into the Part instance (then you'll not have to assign an array instead of a non-array).

I understand you a little, how can I make it?

I don't know if you refer a it:

$part = $robots->id_robots; ? ?

I should assign the robot_id into the Part instance (then you'll not have to assign an array instead of a non-array).



33.8k

If we have 5 parts for a robot (1:5):

foreach($parts as $part) {
    $part->robot_id = $robot->id;
}