mysql - Doctrine 2 : Use default 0 values instead of null for relation

标签 mysql doctrine-orm doctrine

对于 Doctrine 2 的关系(多对一、一对一)是否可以使用值 0 而不是 null?

现在我有很多 NOT NULL 列,但我可能不会更改为空值。 将 MySQL 中的默认值更改为 0 本身并不是解决方案,因为 Doctrine 总是设置用于插入/更新行的列。

最佳答案

不,这是不可能的。

NULL 在 SQL 中有非常特殊的含义。它代表“没有值(value)”,你可以验证你的逻辑即使在 SQL 级别也不会工作:

CREATE TABLE foo (
    `id` INT(11) PRIMARY KEY AUTO_INCREMENT,
    `bar_id` INT(11)
);

CREATE TABLE `bar` (`id` INT(11) PRIMARY KEY AUTO_INCREMENT);

ALTER TABLE foo ADD FOREIGN KEY `bar_id_fk` (`bar_id`) REFERENCES `bar` (`id`);

INSERT INTO `bar` VALUES (NULL);
INSERT INTO `bar` VALUES (NULL);
INSERT INTO `bar` VALUES (NULL);
INSERT INTO `foo` VALUES (NULL, 1);
INSERT INTO `foo` VALUES (NULL, 2);
INSERT INTO `foo` VALUES (NULL, 3);
INSERT INTO `foo` VALUES (NULL, 0);

/*
    ERROR 1452 (23000): 
        Cannot add or update a child row: a foreign key constraint fails
        (`t2`.`foo`, CONSTRAINT `foo_ibfk_1` FOREIGN KEY (`bar_id`) 
        REFERENCES `bar` (`id`))
*/

INSERT INTO `foo` VALUES (NULL, 4);

/*
    ERROR 1452 (23000): 
        Cannot add or update a child row: a foreign key constraint fails
        (`t2`.`foo`, CONSTRAINT `foo_ibfk_1` FOREIGN KEY (`bar_id`) 
        REFERENCES `bar` (`id`))
*/

INSERT INTO `foo` VALUES (NULL, NULL); /* VALID! */

所以不,你不能让 Doctrine ORM 的行为使得 0 被解释为 NULL,因为 RDBMS 本身不允许这样做。

您可以做的是在您的数据库中插入“假”引用条目,然后它将充当 null object当水化为实体时:

INSERT INTO `bar` VALUES (NULL);
UPDATE `bar` SET `id` = 0 WHERE `id` = 4;

INSERT INTO `foo` VALUES (NULL, 0); /* now works! */

在实体方面,它看起来很相似。

(请注意,public 属性仅受尚未发布的 Doctrine ORM 2.4 支持。不过,它们使这里的内容更易于阅读)

Foo.php:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table(name="foo")
 */
class Foo
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @ORM\ManyToOne(targetEntity="Bar")
     * @ORM\JoinColumn(name="bar_id", referencedColumnName="id", nullable=false)
     */
    public $bar;
}

酒吧.php:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table(name="bar")
 */
class Bar
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;
}

然后是生成新的 Foo 实例的代码:

$nullBar  = $entityManager->find('Bar', 0);
$foo      = new Foo();
$foo->bar = $nullBar;

$em->persist($foo);
$em->flush();

关于mysql - Doctrine 2 : Use default 0 values instead of null for relation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15502408/

相关文章:

php - 使用 ajax 重新加载页面以创建实时聊天

Doctrine - BaseClassName 未找到

mysql - 在 MySQL 上通过 polylang 语言查询 wordpress 帖子

php - 出生日期仅按升序排列的月份和日期

php - 从 PHP 调用时与从 Mysql Shell 调用时的 Mysqli 查询结果不同

mysql - Doctrine2 One2Many 相关实体过滤结果

php - 每个 Action 中的线条相同 - 我应该让他们这样做吗? - 交响乐2

php - 在学说 2 中选择日期之间的条目

php - Symfony 2 的 Jobeet

php - 从 Doctrine_Collection 中删除项目