2

I am currently working on two website with Symfony, which has some of each database in common. We created a bundle to contain the database of the main website, and the second one has its own database. Each of the websites have a set of users in their database (not the same), and FOSUserBundle is correctly set up.

I'm trying to create a command that migrates some users of the second website to the main one, and for every user, I want to check if it already exists in the database.

If my database was local, I'd probably do something like $email_exist = $userManager->findUserByEmail($email);, but I don't have acces to the userManager of the other website. I tried:

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

I even created a custom function in my repository that did the same thing and everytime I get the error Entity 'BugTracker\ModelBundle\Entity\User' has no field 'email'. You can therefore not call 'findByEmail' on the entities' repository.

I am absolutly positive that I do have an email and a username field in my database (I tried both). I also tried with id instead of email and it worked so the issue is really with that field in particular.

I'm using FOSUserBundle, and my user class extends BaseUser (that's where the username and email come from)

Is there any (simple) way to do this? Without having to add a new user provider.

Please don't tell me "you shouldn't do that" or that I should only have 1 database, it is not usefull and I can't change it anyway.

My user entity:

<?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();
    }
}

the user entity metadata :

{
"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 configuration on the second website

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
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Liora Haydont
  • 1,252
  • 1
  • 12
  • 25

2 Answers2

1

What if you use username instead of email, because according to your posted entity email property exist in parent class FOS\UserBundle\Model\User and your child class sets email like setEmail(){....} in this function it also sets the same value to username parent::setUsername($email); so i guess you can get the user by using username property

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

Or eles define email property in your class like you defined username property

/**
 * @var string
 * @ORM\Column(type="string" definition....)
 */
protected $email;
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • Everything I tried with email I tried it with username too... The username I added to the entity was a test and it made my command work but gave me an exception when I tried opening the website (field duplicata) so I had to remove it and find another solution. I'll remove it from the question. – Liora Haydont Dec 08 '17 at 13:44
0

From your description, my best guess is that FOSUserBundle `s doctrine xml mappings for the BaseUser are not loaded.

That `s the reason the "email" field is not found.

From what I understand, you do not want to use the bundle for security in your main website. So I assume you did not do step 2 or steps 4-7 of the documentation for the main website.

The easiest way to overcome this, I would suggest is to:

From the added info, the issue is that you are trying to use FOSUserBundle with 2 entity managers. There is already a question about this.

My suggestion is to register the FOSUserBundle `s doctrine mapping manually, as descibed here, by adding:

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

where bugtracker is the name of your entity manager definition.

Jannes Botis
  • 11,154
  • 3
  • 21
  • 39
  • Hello! I think it was unclear in my question, but I have a user entity for each of the websites, and FOS user bundle is set up correctly on each of them, the issue is I'm trying to access the users of the 1st website by username from the second, but the user manager only works on the current website's users. – Liora Haydont Apr 21 '18 at 13:01
  • @LioraHaydont can you try $meta = $emBug->getMetadataFactory()->getMetadataFor(User::class); return new JsonResponse($meta); in an action in a controller? Can you somehow add this output? I want to see if the field mappings are read from doctrine.xml. – Jannes Botis Apr 21 '18 at 13:11
  • I added it to the question. – Liora Haydont Apr 21 '18 at 13:26
  • @LioraHaydont it seems the base mapping is ignored. If I understand correctly, you use 2 entity managers. Can you add the doctrine configuration in your config.yml? – Jannes Botis Apr 21 '18 at 13:38
  • 1
    Yes, on the second website I have a manager for each of the databases. I added the config to the question. – Liora Haydont Apr 21 '18 at 13:47
  • @LioraHaydont Thanks for the info. I added another solution to my answer. – Jannes Botis Apr 21 '18 at 14:05
  • I had to use `mappings` instead of `mapping` and change a little the path to fit my version of FOS but it worked! Thank you. :) – Liora Haydont Apr 21 '18 at 15:09