Skip to content

Instantly share code, notes, and snippets.

@phalcon
Last active December 11, 2015 02:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phalcon/4532426 to your computer and use it in GitHub Desktop.
Save phalcon/4532426 to your computer and use it in GitHub Desktop.
<?php
class Robots extends Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany('id', 'RobotsParts', 'robots_id');
}
}
class Parts extends Phalcon\Mvc\Model
{
}
class RobotsParts extends Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo('robots_id', 'Robots', 'id');
$this->belongsTo('parts_id', 'Parts', 'id');
}
}
<?php
//Querying a robot, Querying a part, creating a robots_parts, saving all together
$robot = Robots::findFirst();
$part = Parts::findFirst();
$robotPart = new RobotsParts();
$robotPart->robots = $robot;
$robotPart->parts = $part;
if(!$robotPart->save()){
var_dump($robotPart->getMessages());
}
<?php
$part = Parts::findFirst();
//Creating a robot part, creating a robot, saving the robot and its part
$robotPart = new RobotsParts();
$robotPart->parts_id = $part->id;
$robot = new Robots();
$robot->type = "Future";
$robot->name = "Bender";
$robot->year = 1999;
$robot->robotsParts = $robotPart;
if(!$robot->save()){
$messages = $robot->getMessages();
var_dump((string) $messages[0]);
}
<?php
$part1 = Parts::findFirst(1);
$part2 = Parts::findFirst(2);
//Creating a robot part, creating a robot, saving the robot and its multiple parts
$robotPart = new RobotsParts();
$robotPart->parts_id = $part->id;
$robotPart1 = new RobotsParts();
$robotPart1->parts_id = $part1->id;
$robotPart2 = new RobotsParts();
$robotPart2->parts_id = $part2->id;
$robot = new Robots();
$robot->type = "Future";
$robot->name = "Bender";
$robot->year = 1999;
$robot->robotsParts = array($robotPart1, $robotPart2);
if(!$robot->save()){
$messages = $robot->getMessages();
var_dump((string) $messages[0]);
}
<?php
//Creating a robot, creating a part, creating a robots_parts, saving all together
$robot = new Robots();
$robot->type = "Future";
$robot->name = "Bender";
$robot->year = 1999;
$part = new Parts();
$part->name = "Arms";
$robotPart = new RobotsParts();
$robotPart->robots = $robot;
$robotPart->parts = $part;
if(!$robotPart->save()){
var_dump($robotPart->getMessages());
}
<?php
$di = new Phalcon\DI();
$di['db'] = new Phalcon\Db\Adapter\Pdo\Mysql(array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'phalcon_test'
));
$di['modelsManager'] = new Phalcon\Mvc\Model\Manager();
$di['modelsMetadata'] = new Phalcon\Mvc\Model\MetaData\Memory();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment