1

问题:

我正在开发一个 WordPress Symfony 包并为其创建实体。

我有一个Comment实体,并$comment->user映射到一个User实体。

然而WordPress0用来代表一个来宾用户。它在 Doctrine 中引起了很多问题,因为 id 为 0 的用户永远不存在。它会导致以下问题:

  • $comment->getUser()user_id当该行是时,可能会引发实体未找到异常0
  • $comment->setUser()不起作用,因为您不能使用nullrepensent guest(应该使用0),并且您也不能使用new User(0)

问题:

默认情况下,以下代码将保存nulluser_id数据库中的列:

$comment->setUser(null);

是否可以将 Doctrine 保存0(而不是null)到user_id列?

或者更好的是,我可以0null处理user_id列时交换吗?

感谢您的时间。

测试用例:

// if a guest posted a comment, pass null to setUser()
// although the actual value will be saved to user_id column is 0
$guestComment->setUser(null);

// if a comment was posted by a guest, getUser() should return null
// although the actual value returned by user_id column is 0
$guestComment->getUser(); // return null

// if a member posted a comment, pass a User entity to setUser()
$memberComment->setUser(new User());

// if a comment was posted by a member, getUser() should return the User entity
$guestComment->getUser(); // return User entity.

方向:

我正在考虑创建自定义映射类型 http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html

4

2 回答 2

2

结果我通过创建自定义类型解决了这个问题:

https://github.com/kayue/WordpressBundle/blob/master/Types/WordPressIdType.php

<?php

/**
 * Datatype for WordPress's IDs
 *
 * WordPress use 0 to represent a guest user. It cause a lots of problems
 * in Doctrine because the user with id zero never exist. This datatype
 * convert 0 to null, make life easier.
 */

namespace Hypebeast\WordpressBundle\Types;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\BigIntType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class WordPressIdType extends BigIntType
{
    const NAME = 'wordpressid';

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if($value === 0) {
            return null;
        }

        return $value;
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if($value === null) {
            return 0;
        }

        return $value;
    }

    public function getName()
    {
        return self::NAME;
    }
}
于 2012-06-24T03:29:58.663 回答
-1

是的,这很简单。

只需将您的setUser函数替换为将 0 转换为 null 的函数,并将您的getUser函数替换为将 null 转换为 0 的函数。

public function setUser($user) {
    if($user == 0) {
        $user = null;
    }

    $this->user = $user;
}

public function getUser() {
    return $this->user == null ? 0 : $this->user;
}

Doctrine 2 不会以任何方式限制您的 getter 和 setter 可以做什么。(或您实体中的任何方法)

于 2012-06-23T12:50:06.017 回答