无法通过捆绑包中的数据库中的用户名或电子邮件找到用户

Can't find user by username or email from database in bundle

我目前正在使用 Symfony 开发两个网站,每个数据库都有一些共同点。我们创建了一个包来包含主网站的数据库,第二个有自己的数据库。每个网站在其数据库中都有一组用户(不相同),并且 FOSUserBundle 已正确设置。

我正在尝试创建一个命令,将第二个网站的一些用户迁移到主要网站,对于每个用户,我想检查它是否已经存在于数据库中。

如果我的数据库是本地的,我可能会做类似 $email_exist = $userManager->findUserByEmail($email); 的事情,但我无权访问其他网站的 userManager。 我试过了:

$emBug->getRepository('BugTrackerModelBundle:User')->findByEmail($email)
$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('email' => $email))

我什至在我的存储库中创建了一个自定义函数来做同样的事情,但每次我都收到错误 Entity 'BugTracker\ModelBundle\Entity\User' has no field 'email'. You can therefore not call 'findByEmail' on the entities' repository

我绝对肯定我的数据库中确实有一个电子邮件和一个用户名字段(我都试过了)。我也尝试使用 id 而不是 email 并且它起作用了,所以问题确实与该字段有关。

我正在使用 FOSUserBundle,我的用户 class 扩展了 BaseUser(这是用户名和电子邮件的来源)

有什么(简单的)方法可以做到这一点吗?无需添加新的用户提供商。

请不要告诉我“你不应该那样做”或者我应该只有 1 个数据库,它没有用而且我也无法更改它。

我的用户实体:

<?php

namespace BugTracker\ModelBundle\Entity;

use BugTracker\ModelBundle\Entity\Project\ProjectToUser;
use BugTracker\ModelBundle\Entity\Authority\AuthorityToUser;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File as BaseFile;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Class User
 *
 * @ORM\Table(name="user")
 * @UniqueEntity(fields={"email"}, message="A user with same email already exists")
 * @ORM\Entity(repositoryClass="BugTracker\ModelBundle\Repository\UserRepository")
 * @Vich\Uploadable
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var bool
     * @ORM\Column(type="boolean")
     */
    protected $deleted;

    /**
     * @var bool
     * @ORM\Column(name="notify", type="boolean", options={"default" : 1}, nullable=true)
     */
    protected $notify;

    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=255, nullable=true)
     */
    protected $firstName;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255, nullable=true)
     */
    protected $lastName;

    /**
     * @var string
     * @ORM\Column(name="job_title", type="string", length=255, nullable=true)
     */
    protected $jobTitle;

    /**
     * @var BaseFile|UploadedFile
     *
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="image")
     */
    protected $userImage;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", nullable=true)
     */
    protected $image;

    /**
     * @var Company
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Company", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $company;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project", mappedBy="createdBy")
     */
    protected $projects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project\ProjectToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedProjects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Authority\AuthorityToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedAuthorities;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    protected $updatedAt;

    /**
     * @var Country
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Country", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $country;

    /**
     * @var string
     *
     * @ORM\Column(name="time_zone", type="string", nullable=true)
     */
    protected $timeZone;

    /**
     * @var string
     *
     * @ORM\Column(name="user_role", type="string", nullable=false)
     */
    protected $userRole;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->enabled = true;
        $this->deleted = false;
        $this->notify = true;

        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();

        $this->projects = new ArrayCollection();
        $this->assignedProjects = new ArrayCollection();
        $this->assignedAuthorities = new ArrayCollection();
    }
}

用户实体元数据:

{
"name":"BugTracker\ModelBundle\Entity\User",
"namespace":"BugTracker\ModelBundle\Entity",
"rootEntityName":"BugTracker\ModelBundle\Entity\User",
"customGeneratorDefinition":null,
"customRepositoryClassName":"BugTracker\ModelBundle\Repository\UserRepository",
"isMappedSuperclass":false,
"isEmbeddedClass":false,
"parentClasses":[

],
"subClasses":[

],
"embeddedClasses":[

],
"namedQueries":[

],
"namedNativeQueries":[

],
"sqlResultSetMappings":[

],
"identifier":[
    "id"
],
"inheritanceType":1,
"generatorType":4,
"fieldMappings":{
    "id":{
        "fieldName":"id",
        "type":"integer",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "id":true,
        "columnName":"id"
    },
    "deleted":{
        "fieldName":"deleted",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"deleted"
    },
    "notify":{
        "fieldName":"notify",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "options":{
            "default":1
        },
        "columnName":"notify"
    },
    "firstName":{
        "fieldName":"firstName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"first_name"
    },
    "lastName":{
        "fieldName":"lastName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"last_name"
    },
    "jobTitle":{
        "fieldName":"jobTitle",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"job_title"
    },
    "image":{
        "fieldName":"image",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"image"
    },
    "createdAt":{
        "fieldName":"createdAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"created_at"
    },
    "updatedAt":{
        "fieldName":"updatedAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"updated_at"
    },
    "timeZone":{
        "fieldName":"timeZone",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"time_zone"
    },
    "userRole":{
        "fieldName":"userRole",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"user_role"
    }
},
"fieldNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "first_name":"firstName",
    "last_name":"lastName",
    "job_title":"jobTitle",
    "image":"image",
    "created_at":"createdAt",
    "updated_at":"updatedAt",
    "time_zone":"timeZone",
    "user_role":"userRole"
},
"columnNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "firstName":"first_name",
    "lastName":"last_name",
    "jobTitle":"job_title",
    "image":"image",
    "createdAt":"created_at",
    "updatedAt":"updated_at",
    "timeZone":"time_zone",
    "userRole":"user_role"
},
"discriminatorValue":null,
"discriminatorMap":[

],
"discriminatorColumn":null,
"table":{
    "name":"user"
},
"lifecycleCallbacks":[

],
"entityListeners":[

],
"associationMappings":{
    "company":{
        "fieldName":"company",
        "joinColumns":[
            {
                "name":"company_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\ModelBundle\Entity\Company",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "company_id":"id"
        },
        "joinColumnFieldNames":{
            "company_id":"company_id"
        },
        "targetToSourceKeyColumns":{
            "id":"company_id"
        },
        "orphanRemoval":false
    },
    "projects":{
        "fieldName":"projects",
        "mappedBy":"createdBy",
        "targetEntity":"BugTracker\ModelBundle\Entity\Project",
        "cascade":[

        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":false,
        "isCascadePersist":false,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false
    },
    "assignedProjects":{
        "fieldName":"assignedProjects",
        "mappedBy":"user",
        "targetEntity":"BugTracker\ModelBundle\Entity\Project\ProjectToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "assignedAuthorities":{
        "fieldName":"assignedAuthorities",
        "mappedBy":"user",
        "targetEntity":"BugTracker\ModelBundle\Entity\Authority\AuthorityToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "country":{
        "fieldName":"country",
        "joinColumns":[
            {
                "name":"country_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\ModelBundle\Entity\Country",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "country_id":"id"
        },
        "joinColumnFieldNames":{
            "country_id":"country_id"
        },
        "targetToSourceKeyColumns":{
            "id":"country_id"
        },
        "orphanRemoval":false
    },
    "groupUsers":{
        "fieldName":"groupUsers",
        "mappedBy":"user",
        "targetEntity":"BugTracker\ModelBundle\Entity\Group\GroupUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\ModelBundle\Entity\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    }
},
"isIdentifierComposite":false,
"containsForeignIdentifier":false,
"idGenerator":{

},
"sequenceGeneratorDefinition":null,
"tableGeneratorDefinition":null,
"changeTrackingPolicy":1,
"isVersioned":null,
"versionField":null,
"cache":null,
"reflClass":{
    "name":"BugTracker\ModelBundle\Entity\User"
},
"isReadOnly":false,
"reflFields":{
    "id":{
        "name":"id",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "deleted":{
        "name":"deleted",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "notify":{
        "name":"notify",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "firstName":{
        "name":"firstName",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "lastName":{
        "name":"lastName",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "jobTitle":{
        "name":"jobTitle",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "image":{
        "name":"image",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "createdAt":{
        "name":"createdAt",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "updatedAt":{
        "name":"updatedAt",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "timeZone":{
        "name":"timeZone",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "userRole":{
        "name":"userRole",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "company":{
        "name":"company",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "projects":{
        "name":"projects",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "assignedProjects":{
        "name":"assignedProjects",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "assignedAuthorities":{
        "name":"assignedAuthorities",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "country":{
        "name":"country",
        "class":"BugTracker\ModelBundle\Entity\User"
    },
    "groupUsers":{
        "name":"groupUsers",
        "class":"BugTracker\ModelBundle\Entity\User"
    }
}
}

二站doctrine配置

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8
            bugtracker:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host_bugtracker%'
                port: '%database_port_bugtracker%'
                dbname: '%database_name_bugtracker%'
                user: '%database_user_bugtracker%'
                password: '%database_password_bugtracker%'
                charset: UTF8

如果您使用用户名而不是电子邮件怎么办,因为根据您发布的实体电子邮件 属性 存在于 parent class FOS\UserBundle\Model\User 和您的 child class 在此函数中像 setEmail(){....} 一样设置电子邮件它也为用户名 parent::setUsername($email); 设置相同的值所以我想你可以通过使用 username 属性

$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('username' => $email));

或者 eles 在您的 class 中定义电子邮件 属性 就像您定义用户名 属性

/**
 * @var string
 * @ORM\Column(type="string" definition....)
 */
protected $email;

根据您的描述,我最好的猜测是 FOSUserBundle 的学说 xml 映射 未加载 BaseUser .

这就是找不到 "email" 字段的原因。

据我了解,您不想在您的主网站中使用捆绑包来确保安全。所以我假设你没有为主要网站做 step 2 or steps 4-7 文档。

我建议克服这个问题的最简单方法是:

根据添加的信息,问题是您正在尝试将 FOSUserBundle 与 2 个实体管理器一起使用。已经有关于此的 question

我的建议是手动注册 FOSUserBundle 的原则映射,如 here 所述,通过添加:

doctrine:
    orm:
        entity_managers:
            # ...
            bugtracker:
                mapping:
                    FOSUserBundle:
                        type: xml
                        dir: '%kernel.root_dir%/../vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/doctrine/model'
                        prefix: FOS\UserBundle\Model
                        is_bundle: false # needed as we don't follow the standard convention for bundles

其中 bugtracker 是您的实体管理器定义的名称。