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' )
);
}
}