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

CRUD example with many to many relationship

I am looking for working CRUD example with many to many relationship and using dynamic field form add (something like this: https://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove)

Thanks for help.



43.9k

Hi,

what do you exactly want to do ? Your example is just html + js.



1.4k

Hello,

I want to have example with many to many relationship and I want to know, how to save data from dynamic field form. And then how to edit them. (Sorry my english is not good.) I would like to see working CRUD example with many to many relationship.

Thank you for your response.

A Controller

Using the $robot->robotparts = $parts; line, we are using the ALIAS defined in the hasManyToMany and passing an array of Parts

<?php

    public function create($slug)
    {

        $parts = array();
        $robotPart =new \App\Models\Parts();        
        $robotPart->name = $slug."Part";    
        $parts[] = $robotPart;

        $robot =new \App\Models\Robots();
        $robot->name = $slug;
        $robot->type = "R2";
        $robot->year = "1978";
        $robot->price = "33.22";
        $robot->robotparts = $parts;

        if ($robot->save() === false) {
            echo "Umh, We can't store robots right now: \n";

            $messages = $robot->getMessages();

            foreach ($messages as $message) {
                echo $message, "\n";
            }
        } else {
            echo "Great, a new robot was saved successfully!";
        }

    }

Model

<?php

namespace App\Models;

use InvalidArgumentException;
use Phalcon\Mvc\Model;

class Robots extends Model
{

    public function initialize()
    {
        $this->setSource("robots");

        $this->hasManyToMany(
            'id',
            "App\Models\RobotsParts",
            'robots_id',
             "parts_id",
            "App\Models\Parts",
            "id",
            array( 'alias' => 'robotparts' )
        );

    }
}

and

<?php

namespace App\Models;

use Phalcon\Mvc\Model;

class Parts extends Model
{

    public function initialize()
    {
        $this->hasMany(
            "id",
            "App\Models\RobotsParts",
            "parts_id",
            array( 'alias' => 'robotparts' )
        );
    }
}