Symfony ManyToOne relation change type

I have 2 entities when 1 is managed by Symfony and other is not

Entity not managed by Symfony

namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * User
 *
 * @ORMTable(name="p_user")
 * @ORMEntity(repositoryClass="AppRepositoryUserRepository")
 */
class User
{
    /**
     * @var int
     *
     * @ORMColumn(name="user_id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var Permission
     *
     * @ORMManyToOne(targetEntity="Permission", inversedBy="user", cascade={"persist", "remove"})
     * @ORMJoinColumn(name="permission_id", referencedColumnName="permission_id", onDelete="CASCADE")
     */
    private $permission;
}

Entity managed by Symfony

namespace AppEntity;

use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;

/**
 * Permission
 *
 * @ORMTable(name="p_permission")
 * @ORMEntity(repositoryClass="AppRepositoryPermissionRepository")
 */
class Permission
{
    /**
     * @var int
     *
     * @ORMColumn(name="permission_id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var ArrayCollection
     *
     * @ORMOneToMany(targetEntity="User", mappedBy="permission", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    private $user;
}

I need to save User entity but permission can’t be null, when no relation, value is set to 0.

After my research i find that User::permission is receiving type of Permission::id, but i want that User::permission type to be nullidentity

PS: NullIdentityType

namespace AppDBALTypesNull;

use DoctrineDBALTypesIntegerType as DeafaultType;
use DoctrineDBALPlatformsAbstractPlatform;

class IdentityType extends DeafaultType
{
    const NULLIDENTITY = 'nullidentity';

    public function getName()
    {
        return self::NULLIDENTITY;
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        // dd($this);
        return $value === null? 0: (int)$value;
    }

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

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *