hasOne relations not properly working tested on debian 8 php 7.
Expected and Actual Behavior
I'm trying to use the hasOne relations on MYSQL and they doesn't work.
I haven't tried them on another database engine but this is the one I need to use right now.
I'm sorry for this explanation but it really seems the case, i've tried to use them with the intended way of use and It doesn't seems to work.
If you use a not null foreign key it fails because for what i've read from (model.zep@2670) it only "pre saves" the related object with the belongsTo relation so it would never work with this structure.
If you use a nulleable foreign key it inserts the "master" row with a null value on the FK field, then it inserts the "slave" row and for what read from (model.zep@2815) it sets the value on the object but it doesn't update the row in the database; you can see this behavior with the test provided script. With this approach the model should perform an update on the "master" with the id from the new record inserted on "slave".
I've prepared both PHP and SQL files to reproduce this. you need to create a database "test_has_one" and a user phalcon with password phalcon or modify it to meet your system.
Maybe the best way to see the issue is to read the script, the schema, and give it a try.
File: bootstrap.php
<?php
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\PDO\Mysql as MysqlAdapter;
use Phalcon\Logger\Adapter\Stream as StreamLogger;
$di = new FactoryDefault();
$di->setShared('logger', function() {
return new StreamLogger("php://stdout");
});
$di->setShared('db', function () {
$eventsManager = $this->get('eventsManager'); /* @var $eventsManager \Phalcon\Events\Manager */
$logger = $this->get('logger');
// Listen all the database events
$eventsManager->attach(
"db:beforeQuery",
function ($event, $connection) use ($logger) {
$logger->log(
$connection->getSQLStatement(),
\Phalcon\Logger::DEBUG
);
}
);
$connection = new MysqlAdapter([
'host' => 'localhost',
'username' => 'phalcon',
'password' => 'phalcon',
'dbname' => 'test_has_one',
'charset' => 'latin1'
]);
// We initialize the database with the structure provided.
$connection->execute(file_get_contents('structure.sql'));
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);
return $connection;
});
/**
* "Primary" class to be related with "Secondary"
*/
class Primary extends \Phalcon\Mvc\Model {
/**
*
* @var int The PK.
*/
public $id_primary;
/**
*
* @var string Some data.
*/
public $data;
}
/**
* "Secondary" class with a hasOne relation to "Primary"
*
* @property Primary $primary magic attribute generated by phalcon.
* @method Primary getPrimary() magic method generated by phalcon.
*/
class Secondary extends \Phalcon\Mvc\Model {
/**
*
* @var int The PK.
*/
public $id_secondary;
/**
*
* @var int The FK to Primary.
*/
public $id_primary;
/**
*
* @var string Some other data.
*/
public $data;
/**
* Sets the relationship
*/
public function initialize() {
$this->hasOne(
"id_primary",
"Primary",
"id_primary"
);
}
}
$logger = $di->get('logger'); /* @var $logger Phalcon\Logger\Adapter\Stream */
//Create new instance of Primary and set some data.
$primary = new Primary();
$primary->data = "Some data.";
//Create new instance of Secondary, set the relation to Primarry
//and set some other data.
$secondary = new Secondary();
$secondary->data = "Some other data.";
$secondary->primary = $primary;
/**
* Auxiliary function declare for test purposes only.
*
* @param Secondary $secondary The Secondary instance to be saved.
* @param StreamLogger $logger The logger to be used.
*/
function secondary_save($secondary, $logger) {
if (!$secondary->save()) {
$logger->error('Umh, We can\'t store "{class}" right now.',
["class" => get_class($secondary)]);
foreach ($secondary->getMessages() as $message) { /* @var $message Phalcon\Mvc\Model\Message */
$logger->error('[MESSAGES] Code: "{code}", Type: "{type}, "Model: {model}, Field: "{field}", Message: "{message}"', [
"model" => $message->getModel(),
"type" => $message->getType(),
"message" => $message->getMessage(),
"field" => $message->getField(),
"code" => $message->getCode(),
]);
}
} else {
$logger->info('Great, a new "{class}" was saved successfully!',
["class" => get_class($secondary)]);
$logger->info('Asociated Primary instance on Secondary id_primary {id_primary}',
["id_primary" => $secondary->primary->id_primary]);
$fetchedSecondary = Secondary::findFirst("id_secondary = '$secondary->id_secondary'");
$logger->info('This value of id_primary should be the same as before, but it\'s not: {id_primary}',
["id_primary" => ($fetchedSecondary->id_primary === null) ? "null" : $fetchedSecondary->id_primary]);
}
}
$logger->info("Phalcon: {phalcon_version}, PHP: {php_version}", [
"phalcon_version" => Phalcon\Version::get(),
"php_version" => phpversion()
]);
$logger->debug('We try to save the Secondary instance with a not null restriction on it\'s hasOne relation.');
secondary_save($secondary, $logger);
$logger->debug('We alter the database to remove the not null restriction to "id_primary" on "secondary" table.');
$connection = $secondary->getWriteConnection();
$connection->execute('ALTER TABLE `secondary` MODIFY COLUMN `id_primary` INT DEFAULT NULL;');
$logger->debug("We clear the model's metadata to get an updated one with the model changed.");
$modelsMetadata = $di->get('modelsMetadata'); /* @var $modelsMetadata \Phalcon\Mvc\Model\MetaData\Memory */
$modelsMetadata->reset();
$logger->debug('We try again, but it doesn\'t update the database after the insert.');
secondary_save($secondary, $logger);
Output
$ php bootstrap.php
[Fri, 10 Mar 17 17:49:57 +0000][INFO] Phalcon: 3.0.4, PHP: 7.0.16-1~dotdeb+8.1
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] We try to save the Secondary instance with a not null restriction on it's hasOne relation.
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] SELECT IF(COUNT(*) > 0, 1, 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` = 'secondary' AND `TABLE_SCHEMA` = DATABASE()
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] DESCRIBE `secondary`
[Fri, 10 Mar 17 17:49:57 +0000][ERROR] Umh, We can't store "Secondary" right now.
[Fri, 10 Mar 17 17:49:57 +0000][ERROR] [MESSAGES] Code: "0", Type: "PresenceOf, "Model: , Field: "id_primary", Message: "id_primary is required"
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] We alter the database to remove the not null restriction to "id_primary" on "secondary" table.
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] ALTER TABLE `secondary` MODIFY COLUMN `id_primary` INT DEFAULT NULL;
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] We clear the model's metadata to get an updated one with the model changed.
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] We try again, but it doesn't update the database after the insert.
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] SELECT IF(COUNT(*) > 0, 1, 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` = 'secondary' AND `TABLE_SCHEMA` = DATABASE()
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] DESCRIBE `secondary`
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] INSERT INTO `secondary` (`id_primary`, `data`) VALUES (DEFAULT, ?)
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] SELECT IF(COUNT(*) > 0, 1, 0) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` = 'primary' AND `TABLE_SCHEMA` = DATABASE()
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] DESCRIBE `primary`
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] INSERT INTO `primary` (`data`) VALUES (?)
[Fri, 10 Mar 17 17:49:57 +0000][INFO] Great, a new "Secondary" was saved successfully!
[Fri, 10 Mar 17 17:49:57 +0000][INFO] Asociated Primary instance on Secondary id_primary 2
[Fri, 10 Mar 17 17:49:57 +0000][DEBUG] SELECT `secondary`.`id_secondary`, `secondary`.`id_primary`, `secondary`.`data` FROM `secondary` WHERE `secondary`.`id_secondary` = '1' LIMIT :APL0
[Fri, 10 Mar 17 17:49:57 +0000][INFO] This value of id_primary should be the same as before, but it's not: null
Details
- Phalcon version:
phalcon
Web framework delivered as a C-extension for PHP
phalcon => enabled
Author => Phalcon Team and contributors
Version => 3.0.4
Build Date => Feb 20 2017 19:31:17
Powered by Zephir => Version 0.9.6a-dev-aef205594b
Directive => Local Value => Master Value
phalcon.db.escape_identifiers => On => On
phalcon.db.force_casting => Off => Off
phalcon.orm.events => On => On
phalcon.orm.virtual_foreign_keys => On => On
phalcon.orm.column_renaming => On => On
phalcon.orm.not_null_validations => On => On
phalcon.orm.exception_on_failed_save => Off => Off
phalcon.orm.enable_literals => On => On
phalcon.orm.late_state_binding => Off => Off
phalcon.orm.enable_implicit_joins => On => On
phalcon.orm.cast_on_hydrate => Off => Off
phalcon.orm.ignore_unknown_columns => Off => Off`
- PHP Version:
PHP 7.0.16-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.16-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend Technologies
- Operating System:
Linux debian-desktop 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u1 (2017-02-22) x86_64 GNU/Linux
- Installation type:
installed via package manager
- Zephir version (if any):
none
- Server: Nginx | Apache | Other
not needed to test.
- Other related info (Database, table schema):
Provided structure.sql
-- MySQL dump 10.13 Distrib 5.7.17, for Linux (x86_64)
--
-- Host: localhost Database: test_has_one
-- ------------------------------------------------------
-- Server version 5.7.17
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `primary`
--
DROP TABLE IF EXISTS `primary`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `primary` (
`id_primary` int(11) NOT NULL AUTO_INCREMENT,
`data` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id_primary`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `secondary`
--
DROP TABLE IF EXISTS `secondary`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `secondary` (
`id_secondary` int(11) NOT NULL AUTO_INCREMENT,
`id_primary` int(11) NOT NULL,
`data` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id_secondary`),
KEY `id_primary_FOREIGN` (`id_primary`),
CONSTRAINT `secondary_ibfk_1` FOREIGN KEY (`id_primary`) REFERENCES `primary` (`id_primary`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-03-10 13:58:12
You should use belongsTo, not hasOne, hasOne is for accessing secondary from primary for example. Pretty much hasOne is for same case as hasMany, but instead of resultset it returns only one record.
Next time for questions about how to use something use forum - https://forum.phalconphp.com
Also you forgot to set ["alias" => "primary"] in options.