MySQL
SET GLOBAL general_log = 'ON';
SET GLOBAL general_log_file = '/var/log/mysql/debug.log';
PHP
class RobotsParts extends Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo(
'parts_id',
Parts::class,
'id',
[
'alias' => 'parts',
]
);
$this->belongsTo(
'robots_id',
Robots::class,
'id'
);
}
}
class Robots extends Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasManyToMany(
'id',
RobotsParts::class,
'robots_id',
'parts_id',
'Parts',
'id'
);
}
}
class Parts extends Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany(
'id',
RobotsParts::class,
'parts_id'
);
}
}
$di = new Phalcon\Di\FactoryDefault();
$di->set('db', function () {
return new Phalcon\Db\Adapter\Pdo\Mysql([
"host" => "127.0.0.1",
"dbname" => "phalcon_test",
"port" => 3306,
"username" => "root",
"password" => "",
]);
});
$robot = new Robots([
'name' => 'The Tachikomas II',
'type' => 'mechanical',
'year' => 1989,
'datetime' => '1989-01-01 00:00:00',
'text' => 'Ghost in the Shell',
]);
var_dump($robot->getParts()->count());
$parts = [
new Parts(['name' => 'Leg-3']),
new Parts(['name' => 'Hand-3']),
new Parts(['name' => 'Head-3']),
new Parts(['name' => 'Eye-3']),
new Parts(['name' => 'Antenna-3']),
];
$robot->parts = $parts;
var_dump($robot->getParts()->count());
$robot->save();
var_dump($robot->getParts()->count());
$id = $robot->id;
unset($robot);
$robot = Robots::findFirst($id);
var_dump($robot->getParts()->count());
Output
int(0)
int(0)
int(5)
int(5)
cat /var/log/mysql/debug.log | grep "INSERT\|TRANSACTION\|COMMIT" | awk -F'Query' '{print $2}'
START TRANSACTION
INSERT INTO `robots` (`name`, `type`, `year`, `datetime`, `deleted`, `text`) VALUES ('The Tachikomas II', 'mechanical', 1989, '1989-01-01 00:00:00', DEFAULT, 'Ghost in the Shell')
INSERT INTO `parts` (`name`) VALUES ('Leg-3')
INSERT INTO `robots_parts` (`robots_id`, `parts_id`) VALUES ('43', '188')
INSERT INTO `parts` (`name`) VALUES ('Hand-3')
INSERT INTO `robots_parts` (`robots_id`, `parts_id`) VALUES ('43', '189')
INSERT INTO `parts` (`name`) VALUES ('Head-3')
INSERT INTO `robots_parts` (`robots_id`, `parts_id`) VALUES ('43', '190')
INSERT INTO `parts` (`name`) VALUES ('Eye-3')
INSERT INTO `robots_parts` (`robots_id`, `parts_id`) VALUES ('43', '191')
INSERT INTO `parts` (`name`) VALUES ('Antenna-3')
INSERT INTO `robots_parts` (`robots_id`, `parts_id`) VALUES ('43', '192')
COMMIT