Symfony $this->getUser() without doctrine associations (OneToMany) - php

In Symfony, we can get current logged-in user data using $this->getUser(), but my problem is when I access this statement, I am getting all the user-associated data set. which has OneToMany relationships with another entity, and it has a lot of data.
Example:
User Entity
`
class User implements UserInterface
{
/**
* #var string
* #ORM\Id
* #ORM\Column(type="string", length=10)
*
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string")
*/
protected $email;
/**
* #var array
* #ORM\Column(type="json")
*/
protected $roles;
/**
* One User has Many Posts.
* #ORM\OneToMany(targetEntity="App\Entity\Post", mappedBy="user", fetch="LAZY")
*
*
*/
private Collection $posts;
`
Post Entity
`
class Post
{
/**
* #var string
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", length=11)
*/
private $id;
/**
* Many posts have one user.
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="post", fetch="EXTRA_LAZY")
* #ORM\JoinColumn(name="userId", referencedColumnName="id")
*/
private $user;
`
I am looking to get rid of the user-associated data set or limit the associated data set to limit 1.
Thank you for the help in advance. :)

found solution after hours of search.
You will be required to add Symfony Serializer #Ignore attribute on the Entity class.
Example
use Symfony\Component\Serializer\Annotation\Ignore;
class User implements UserInterface
{
/**
* #var string
*
*/
#[ORM\Id]
#[ORM\Column(type: 'string', length: 10)]
protected $id;
/**
* #var string
*/
#[ORM\Column(type: 'string')]
protected $email;
/**
* #var array
*/
#[ORM\Column(type: 'json')]
protected $roles;
/**
* #var Post
*/
#[ORM\OneToMany(targetEntity: 'App\Entity\Post', mappedBy: 'user', fetch: 'LAZY')]
#[Ignore]
private Collection $posts;
I hope this help someone. Cheers!

Related

Doctrine Associations in symfony

so I have been working with Symfony for a while but there is one thing that bothers.
It's about Doctrine Associations.
The thing is that I am trying to achieve a user friend invites and relations and there is a page that the user can see the invitations he sent and the ones that are pending.
EDIT: I made it happen using Many-To-One/One-To-Many associations. However
My question is - Are Doctrine Associations the correct way of doing that.
My User Entity
class User implements UserInterface
{
private $id;
/**
* #ORM\Column(name="first_name", type="string", length=30)
*
* #Assert\NotBlank(message="First name cannot be a blank field", groups={"register"})
* #Assert\Length(min="3", max="30", groups={"register"})
*/
/**
* #ORM\Column(type="string", length=50)
*
* #Assert\NotBlank(message="Username cannot be a blank field", groups={"register"})
* #Assert\Length(min="7", max="50", groups={"register"})
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\Length(min="7", max="50", groups={"register"})
*/
private $password;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserInvitation", mappedBy="inviterId", orphanRemoval=true)
*/
private $userInvitations;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserInvitation", mappedBy="invitedId", orphanRemoval=true)
*/
private $pendingUserInvitations;
//getters and setters
My UserInvitation Entity
class UserInvitation
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="userInvitations")
* #ORM\JoinColumn(name="inviter_id", nullable=false)
*/
private $inviterId;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="pendingUserInvitations")
* #ORM\JoinColumn(name="invited_id", nullable=false)
*/
private $invitedId;
/**
* #ORM\Column(type="boolean")
*/
private $status;
This is my database.
The relationships is the right way to do it although on the entity I would use the following:
class UserInvitation
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="userInvitations")
* #ORM\JoinColumn(name="inviter_id", nullable=false)
*/
private $inviter;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="pendingUserInvitations")
* #ORM\JoinColumn(name="invited_id", nullable=false)
*/
private $invitee;
/**
* #ORM\Column(type="boolean")
*/
private $status;
Then you would getInviter() or setInviter(). Basically think that you are saving the related object to the entity and not the related field

Doctrine : Foreign keys are not generated

The problem I have with doctrine is that after the
php bin/console doctrine:schema:update --force
it creates the DB but not the foreign keys.
I'm using annotations and I tried to use the #ORM\JoinColumn in the ManyToOne ... etc annotations but without success.
I hope you guys can help me.
Here is the code of one of my entities:
<?PHP
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="member")
*/
class Member{
/**
* #ORM\Column(type="string",length=25)
* #ORM\Id
*/
private $code;
/**
* #ORM\Column(type="string",length=25)
*/
private $first_name;
/**
* #ORM\Column(type="string",length=25)
*/
private $last_name;
/**
* #ORM\Column(type="integer")
*/
private $national_id;
/**
* #ORM\Column(type="string",length=25)
*/
private $civil_situation;
/**
* #ORM\Column(type="string",length=1)
*/
private $gender;
/**
* #ORM\Column(type="date")
*/
private $dob;
/**
* #ORM\Column(type="integer")
*/
private $tel_mobile;
/**
* #ORM\Column(type="integer")
*/
private $tel_home;
/**
* #ORM\Column(type="integer")
*/
private $tel_ref;
/**
* #ORM\Column(type="string",length=25)
*/
private $email;
/**
* #ORM\Column(type="date")
*/
private $entry_date;
/**
* #ORM\Column(type="string",length=64)
*/
private $password;
/**
* #ORM\Column(type="integer",nullable=true)
* #ORM\OneToOne(targetEntity="Staff")
*/
private $staff;
/**
* #ORM\Column(type="integer",nullable=true)
* #ORM\OneToOne(targetEntity="Student")
*/
private $student;
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Address")
*/
private $address;
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Faculty")
*/
private $faculty;
/**
* #ORM\Column(type="integer")
*/
private $disable;
/**
* #ORM\Column(type="string",length=25,nullable=true)
*/
private $disable_reason;
/**
* #ORM\Column(type="integer",nullable=true)
*/
private $disable_year;
public function __construct()
{
//nothing
}
// getters and setters
?>
When #ORM\Column is specified along with #ORM\JoinColumn on same column, then JoinColumn's association gets ignored and Foreign Key isn't created on table. so dont use both #ORM\Column and #ORM\JoinColumn in same column.
Do like below:
/**
* #var Address
*
* #ORM\ManyToOne(targetEntity="Address")
* #ORM\JoinColumn(name="address_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $address;
It makes column named address_id on database table, with foreign key index and on deletion of Address record, associated record in dependent table is also deleted(cascade operation). You may user other operation on onDelete, see doctrine's documentation.

Symfony ManyToOne Form add, delete in DB

I have entity developer and comment and relationship Many comment to One developer. And I need form when I see all comment for developer and edit - add, delete in DB . What are the solutions to this problem
entity Comment:
class Comments
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Developer", inversedBy="comments")
* #ORM\JoinColumn(name="talent_id", nullable = true, referencedColumnName="id")
* */
protected $talent;
/**
* #var string
*
* #ORM\Column(name="added_by", type="string", length=10, nullable=true)
*/
private $added_by;
/**
* #var string
*
* #ORM\Column(name="comment", type="string", length=10, nullable=true)
*/
private $comment;
entity Developer:
class Developer extends CustomUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/////
/**
* #ORM\OneToMany(targetEntity="Comments", mappedBy="talent", cascade={"persist", "remove"})
*/
protected $comments;
Maybe need form in form but how to do this?
You are looking for field type collection.
Example usage of collection type
class Comments
{
....
/**
*
*#ORM\ManyToOne(targetEntity="Developer", inversedBy="developer_to_comments")
* #ORM\JoinColumn(name="developer_to_comments_id", referencedColumnName="id", nullable=false)
*
*/
private $comments_to_developer;
...
}
And class Developer
class Developer extends CustomUser
{
....
/**
*
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="Comments", mappedBy="comments_to_developer", cascade={"remove"})
*/
private $developer_to_comments;
public function __construct()
{
$this->developer_to_comments = new ArrayCollection();
}
....
}
And don't forget use Doctrine\Common\Collections\ArrayCollection

Doctrine/Symfony - I have some errors. Something wrong with my relations

I always get an exception with my entities. I tried to play with them. I checked on google which relation is the most appropriate for my entities... But I couldn't find the best configuration.
I'm making a website where you can create some albums.
A user can have multiple albums.So I have an entity Album and I have inside a user property :
/**
* Album
*
* #ORM\Table(name="album")
* #ORM\Entity(repositoryClass="Moodress\Bundle\AlbumBundle\Entity\AlbumRepository")
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
** #ORM\ManyToOne(targetEntity="Moodress\Bundle\UserBundle\Entity\User")
** #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="creationDate", type="datetime")
*/
private $creationDate;
/**
* #var \DateTime
*
* #ORM\Column(name="modificationDate", type="datetime")
*/
private $modificationDate;
/**
* #ORM\OneToMany(targetEntity="Moodress\Bundle\AlbumBundle\Entity\Picture", cascade={"persist"}, mappedBy="album")
*/
private $pictures;
/**
* Constructor
*/
public function __construct()
{
$this->creationDate = new \Datetime();
$this->modificationDate = new \Datetime();
}
// Get and set
}
However, When a user subscribe on the website, I create a default album called Upload that I want to keep in the user class.
This is what I tried to do :
/**
* User
*
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Moodress\Bundle\AlbumBundle\Entity\Album", cascade={"persist"})
*/
protected $albumUpload;
// Get and set
}
I have this error :
Undefined index: album in /Users/Sandro/sites/moodress-website/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1608. This error appears directly when I serialize any entity that has a user object...
The error is caused by the association annotation of the $albumUpload property in the User class.
Doctrine assumes that you have a $album property in your Album entity when you use a #ORM\OneToOne(targetEntity="Moodress\Bundle\AlbumBundle\Entity\Album") association in your User entity.
Try
/**
** #ORM\ManyToOne(targetEntity="Moodress\Bundle\UserBundle\Entity\User", inversedBy="albums")
** #ORM\JoinColumn(nullable=false)
*/
private $user;
in your Album entity and
/**
* #ORM\OneToMany(targetEntity="Moodress\Bundle\AlbumBundle\Entity\Album", mappedBy="user", cascade={"persist"})
*/
protected $albums;
in your User entity. In addition please add $this->albums = new ArrayCollection() to User::__construct().
Now if you want to add and keep a default album for users you should implement this somewhere in your business logic. You could figure out a way to identify the default album in your collection of albums and prevent deletion especially for this item.
Hope this helps.
My error:
'Undefined index: album'
results from this annotation in the Album class.
/**
* #ORM\OneToMany(
* targetEntity="Moodress\Bundle\AlbumBundle\Entity\Picture",
* cascade={"persist"},
* mappedBy="album"
* )
*/
I have set mappedBy to album but there is no $album property in my Picture class.
I did add this to my Picture class and clear my cache.
/**
* #ORM\ManyToOne(
* targetEntity="Moodress\Bundle\AlbumBundle\Entity\Album",
* inversedBy="pictures"
* )
*/
protected $album;
It solved my problem

sonata admin use two entities in an admin

im new to sonata admin, is this possible to use two entities in one admin class?
my User entity,
App\MyBundle\Entity\Users.php
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=45, nullable=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=100, nullable=true)
*/
private $email;
my UserProject entity,
App\MyBundle\Entity\UserProjects.php
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \User
*
* #ORM\ManyToOne(targetEntity="Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="userId", referencedColumnName="id")
* })
*/
private $userid;
/**
* #var array
*
* #ORM\Column(name="projectId", type="array")
*/
private $projects;
my Admin class,
class UserAdmin extends SonataUserAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General') // these fields from Users Entity
->add('username')
->add('email')
->with('Projects') // these fields from UserPrjects Entity
/* here i need to add a field for projects related to current user */
}
}
is there any way to get these two entities connect together?
I suggest you to add a One-To-Many in the User side:
/**
* #ORM\OneToMany(targetEntity="UserProjects", mappedBy="userid")
*/
protected $userProjects;
The you can use the UserProjects entity.

Categories