On my index page are displayed different users. What i want to achieve is when someone click on the username to be redirected on other page where are displayed informations for the user.
Here is part of the twig code which will redirect the user to the hello route.
{% for user in users %}
<strong><em> {{ user.username}}
And this is hello route :
hello:
pattern: /hello
defaults: {_controller:AcmeWebBundle:Default:hello }
I have no idea how to implement this in the contoroler. Can i use variable in which are stored informations for the users from other function or i need to make db query? And how that query to be for particular user who is displayed? In addition is part from the entity. Thanks.
<?php
namespace Acme\Bundle\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* baza
*
* #ORM\Table()
* #ORM\Entity
*/
class baza
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=30)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=30)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="od", type="string", length=30)
*/
private $od;
/**
* #var string
*
* #ORM\Column(name="do", type="string", length=30)
*/
private $do;
/**
* #var float
*
* #ORM\Column(name="cena", type="float")
*/
private $cena;
/**
* #var string
*
* #ORM\Column(name="comment", type="text")
*/
private $comment;
/**
* #var integer
*
* #ORM\Column(name="rating", type="integer")
*/
private $rating;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="car", type="string", length=20)
*/
private $car;
Try this in your template:
{% for user in users %}
<strong><em><a href="{{ path('hello', {"id": user.id}</a>
and this in your routing:
hello:
pattern: /hello/{id}
and your controller will have something like:
public function helloAction(Request $request, $id)
then in your controller retrieve the user by id. This and the rest of it is can be inferred in the book.
Hope this helps
Related
I followed this documentation in sonata, step by step and it worked.
Then I added a new entity and tried to generate a relation many to many to user entity, and when I validate it return this error
$ bin/console doctrine:schema:validate
Mapping
-------
[FAIL] The entity-class AppBundle\Entity\Business mapping is invalid:
* The association AppBundle\Entity\Business#user refers to the owning side field Application\Sonata\UserBundle\Entity\User#business which does not exist.
Database
--------
[OK] The database schema is in sync with the mapping files.
This are my two entities
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Business
*
* #ORM\Table(name="business")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BusinessRepository")
*/
class Business
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="BusinessName", type="string", length=255)
*/
private $businessName;
/**
* #var string
*
* #ORM\Column(name="fantasyName", type="string", length=255)
*/
private $fantasyName;
/**
* #var string
*
* #ORM\Column(name="cuit", type="string", length=13)
*/
private $cuit;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\BankAccountType", inversedBy="business")
*/
private $bankAccountType;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #ORM\ManyToMany(targetEntity="\Application\Sonata\UserBundle\Entity\User", mappedBy="business")
*/
private $user;
/**
* #var bool
*
* #ORM\Column(name="isActive", type="boolean")
*/
private $isActive = true;
And this
namespace Application\Sonata\UserBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* This file has been generated by the SonataEasyExtendsBundle.
*
* #link https://sonata-project.org/easy-extends
*
* References:
* #link http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
*/
class User extends BaseUser
{
/**
* #var int $id
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="\AppBundle\Entity\Business", inversedBy="user")
* #ORM\JoinTable(name="business_user")
*/
private $business;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->business = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return int $id
*/
public function getId()
{
return $this->id;
}
}
Any idea?
Here is my code for the same thing and it works.
class Role
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="wizai\WMC\UserBundle\Entity\User", mappedBy="customRoles", fetch="EAGER")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
}
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="wizai\WMC\UserBundle\Entity\Role", inversedBy="users", fetch="EAGER")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role", referencedColumnName="id")}
* )
*/
protected $customRoles;
/**
* User constructor.
*/
public function __construct()
{
$this->customRoles = new ArrayCollection();
}
}
if its still not possible, can you first run a migration or a force update ?
Commands
bin/console doctrine:migrations:diff
bin/console doctrine:migrations:migrate
if not, then try.
bin/console doctrine:schema:update --force --complete
I was working on an app and had everything set up nicely. I have an Alert entity which takes the following form.
/**
* Alert
*
* #ORM\Table(name="alert")
* #ORM\Entity(repositoryClass="Nick\AlertBundle\Repository\AlertRepository")
*
*/
class Alert
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="search_command", type="string", length=256, nullable=false)
*/
private $searchCommand;
/**
* #var string
*
* #ORM\Column(name="is_connecting", type="string", length=20, nullable=false)
*/
private $isConnecting;
/**
* #var \DateTime
*
* #ORM\Column(name="last_updated", type="datetime", nullable=false)
*/
private $lastUpdated;
/**
* #var boolean
*
* #ORM\Column(name="is_deleted", type="boolean", nullable=false)
*/
private $isDeleted;
/**
* #var string
*
* #ORM\Column(name="alert_status", type="string", length=11, nullable=false)
*/
private $alertStatus;
/**
* #ORM\OneToMany(targetEntity="Nick\AlertBundle\Entity\BookingClass", mappedBy="availabilityAlert")
*/
private $bookingClass;
/**
* #ORM\OneToMany(targetEntity="Nick\AlertBundle\Entity\Pseudos", mappedBy="availabilityAlert")
*/
private $pseudo;
/**
* #ORM\OneToMany(targetEntity="Nick\AlertBundle\Entity\FlightNumbers", mappedBy="availabilityAlert")
*/
private $flightNumbers;
/**
* #ORM\OneToMany(targetEntity="Nick\AlertBundle\Entity\Availability", mappedBy="availabilityAlert")
*/
private $availability;
/**
* Constructor
*/
public function __construct()
{
$this->bookingClass = new ArrayCollection();
$this->pseudo = new ArrayCollection();
$this->flightNumbers = new ArrayCollection();
$this->availability = new ArrayCollection();
}
//other methods
}
So I had this app working, but now I have decided to add a log in system. Each Alert should now be associated to a user - a user can have none to many alerts.
So I have created my user class and set up all the security. The entity looks like
/**
* User
*
* #ORM\Table(name="user_table")
* #ORM\Entity()
*
*/
class User implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
//other functions
}
So whats the best way to associate Alerts to a User? Should I set it up like I do the with the other Entities in my Alert class? Should I add an Alert variable within the user class which is an Array Collection of Alerts?
Really just looking for a bit of advice how to best handle this.
Thanks
Yes you should add one to many relation ship in user entity and link with alert entity and in alert entity point back to user entity in many to one way
class User
{
/**
* #ORM\OneToMany(targetEntity="Alert", mappedBy="user")
*/
protected $alerts;
public function __construct()
{
$this->alerts= new ArrayCollection();
}
//... other getters amd setters
}
class Alert
{
// ...
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="alerts")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
}
Reference
I dont really see here any other solutions besides using ManyToOne association in the Alert entity or ManyToMany in case one Alert has to be associated with more then 1 user.
Should I add an Alert variable within the user class which is an Array Collection of Alerts?
Heck, why not? That way you can easily get users with joined alerts.
I was wondering if it was possible to configure a entity to automatically load data from another entity.
Ex.
/**
* accountsUsers
*
* #ORM\Table()
* #ORM\Entity
*/
class accountsUsers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #var string
*
* #ORM\Column(name="userid",type="integer")
*/
public $userid;
/**
* #var string
*
* #ORM\Column(name="roleid",type="integer")
*/
public $roleid;
/**
* #var string
* admin,adviser,etc
* #ORM\Column(name="roleType", type="string", length=255)
*/
public $roleType;
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255)
*/
public $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255)
*/
public $lastname;
/**
* #var string
*
* #ORM\Column(name="company", type="string", length=255)
*/
public $company;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
public $url;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255)
*/
public $phone;
/**
* #var string
*
* #ORM\Column(name="phone2", type="string", length=255)
*/
public $phone2;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
public $address;
/**
* #var string
*
* #ORM\Column(name="address2", type="string", length=255)
*/
public $address2;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255)
*/
public $city;
/**
* #var string
*
* #ORM\Column(name="state", type="string", length=255)
*/
public $state;
/**
* #var string
*
* #ORM\Column(name="zip", type="string", length=255)
*/
public $zip;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
public $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
public $password;
}
AND
/**
* accounts
*
* #ORM\Table()
* #ORM\Entity
*/
class accounts
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #var string
*
* #ORM\Column(name="partnerid", type="string", length=100)
*/
public $partnerid;
/**
* #var \DateTime
*
* #ORM\Column(name="subscribedate", type="date")
*/
public $subscribedate;
/**
* #var string
*
* #ORM\Column(name="connectionType", type="string", length=100)
*/
public $connectionType;
/**
* #var string
*
* #ORM\Column(name="recordkeeperTpaid", type="string", length=100)
*/
public $recordkeeperTpaid;
/**
* #var string
*
* #ORM\Column(name="recordkeeperAdviceProviderCd", type="string", length=100)
*/
public $recordkeeperAdviceProviderCd;
/**
* #var string
*
* #ORM\Column(name="recordkeeperUrl", type="string", length=200)
*/
public $recordkeeperUrl;
/**
* #var string
*
* #ORM\Column(name="recordkeeperUser", type="string", length=100)
*/
public $recordkeeperUser;
/**
* #var string
*
* #ORM\Column(name="recordkeeperPass", type="string", length=100)
*/
public $recordkeeperPass;
/**
* #var string
*
* #ORM\Column(name="recordkeeperPortfoliosAvailable", type="smallint")
*/
public $recordkeeperPortfoliosAvailable;
/**
* #var string
*
* #ORM\Column(name="recordkeeperRiskBasedFundsAvailable", type="smallint")
*/
public $recordkeeperRiskBasedFundsAvailable;
/**
* #var string
*
* #ORM\Column(name="investmentsMinScore", type="integer")
*/
public $investmentsMinScore;
/**
* #var string
*
* #ORM\Column(name="investmentsMaxScore", type="integer")
*/
public $investmentsMaxScore;
/**
* #var string
*
* #ORM\Column(name="ACAon", type="smallint")
*/
public $ACAon;
/**
* #var string
*
* #ORM\Column(name="MSTClientID", type="string", length = 100)
*/
public $MSTClientID;
}
Is it possible to set up accountsUsers to automatically load in all the accounts data when accountsUsers is accessed by findby, findbyone, etc. The relationship is accountsUsers.userid = accounts.id.
If not, how would I do this in a join using doctrine. I know how to do it using pure raw sql.
Ex. SELECT * FROM accounts a LEFT JOIN accountsUsers b ON a.id =
b.userid
It is not possible to load separate entities in one query (i.e. with a JOIN) just by using annotations. You'll have to define a custom query in your repository which instructs Doctrine, via DQL or QueryBuilder, to join with the related entities.
It was a big gotcha for me as well, but using fetch="EAGER" in the annotation defining the association doesn't actually use a JOIN to retrieve the result - it just issues 2 separate queries to pre-fill the relationship so that its first access does not trigger the lazy loading process.
See also this question for more information.
Symfony developed relations which give you the ability to define a property in entity files and relate it to other entity.
There are two ways.
First way:
In your case,
first you have to make a column in users table(for example name it account) and relate it to account.id column using foreign key's, then in App\Entity\Accounts you can define a property name $users and relate it to App\Entity\Users like code below:
/**
* #ORM\OneToMany(targetEntity="App\Entity\Users", mappedBy="account")
*/
private $users;
and one in App\Entity\Users
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Accounts", inversedBy="users")
*/
private $Account;
like this whenever you get a object from App\Entity\Accounts
a key with the name users will return that have the information of all of this account users just the result:
SELECT * FROM accounts a LEFT JOIN accountsUsers b ON a.id = b.userid
will give you.
The second way is pretty easy just by using make:entity command
php bin/console make:entity
you can make a new column and make a relation for it, command will ask you about everything step by step and its pretty much so simple working with it that you don't need to read the document but if you need more information this is the link to read about it
https://symfony.com/doc/current/doctrine/associations.html#the-manytoone-onetomany-association
How can I add relationship between user and posts using users id? I saw some examples, but I couldn't follow what inversedBy and mappedBy are for... Is it possible to store profile_id and not the object?
User profile entity:
class Profiles
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
Posts/Comments entity:
class Comments
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Profiles
*
* #ORM\ManyToOne(targetEntity="Profiles")
* #ORM\JoinColumn(name="profile_id", referencedColumnName="id")
*/
private $profile;
OK example
///User Enity
/**
* #ORM\OneToMany(targetEntity="Car", mappedBy="user")
*/
private $cars;
// Car Entity
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="cars")
* #ORM\JoinColumn(name="users_id", referencedColumnName="id")
*/
private $user;
So it sill take the user id and populate this against the Car users_id column in that record
So meaning the a user can be associated to many cars
Very very weird. I have used this method from doctrine hundreds of times. I have a simple controller that takes an id as parameter. The query that Doctrine generates is wrong and crash.
/**
* #Security("has_role('ROLE_ADMIN')")
* #return Response
*/
public function editSellerAction($id)
{
$em = $this->getDoctrine()->getManager();
$seller = $em->getRepository('SiteUserBundle:Seller')->find($id);
// ...
$form = $this->createForm(new SellerType(), $seller, array(
'method' => 'POST'
));
// ...
}
The query generated is the following
[2/2] DBALException: An exception occurred while executing 'SELECT t1.id AS id2, t1.username AS username3, t1.password AS password4, t1.firstname AS firstname5, t1.lastname AS lastname6 FROM seller t1 WHERE t0.id = ? LIMIT 1' with params ["2"]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 't0.id' in 'where clause' +
The error thrown makes sense because it's looking at "WHERE t0.id" when it should be looking at "WHERE t1.id". I tried the query with t1 using phpmyadmin and it works.
Any idea what might cause this issue?
/**
* Seller have access to their customer and are able to RW access to the customers
*
* #ORM\Table("seller")
* #ORM\Entity
* #author Michael Villeneuve
*/
class Seller extends User
{
/**
* #var array
*
* #ORM\OneToMany(targetEntity="Customer", mappedBy="seller", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="seller_id", referencedColumnName="id")
**/
protected $customers;
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=false)
*/
protected $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=false)
*/
protected $lastname;
// Other attributes and only getters/setter
/**
*
* #ORM\Entity
*/
class User implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
I have 3 entities that extends the User (customer, admin and seller).
Updated link: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/inheritance-mapping.html
Read up a bit on mapped super classes: http://docs.doctrine-project.org/en/latest/reference/inheritance-mapping.html. Basically, your abstract base user class cannot itself be an entity.
So take the #ORM\Entity line out of your User class. That is where the table 0 (t0) is coming from.
You have 2 options:
The first one is to create an abstract User entity and inherit all values from it. This is useful if you have many entities with the same behaviour. I e.g. like to create a BaseEntity with a ID field and some basic methods. All entities can extend this one and automatically have an ID. Cerad explained in his answer how this is done.
The second option are so called discriminator fields. Basically they allow you to have one User table and sub-tables for every extended entity. You can read about them in the official docs.
Which one you end up using is probably case dependent.
Try to add id field to the Seller entity instead of User
/**
* Seller have access to their customer and are able to RW access to the customers
*
* #ORM\Table("seller")
* #ORM\Entity
*/
class Seller extends User
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var array
*
* #ORM\OneToMany(targetEntity="Customer", mappedBy="seller", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="seller_id", referencedColumnName="id")
**/
protected $customers;
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=false)
*/
protected $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=false)
*/
protected $lastname;
// Other attributes and only getters/setter
/**
*
* #ORM\Entity
* #author Michael Villeneuve<michael#panierdachat.com>
*/
class User implements UserInterface
{
/**
* #ORM\Column(type="string", length=255, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;