How to do a join on two entities in Symfony and Doctrine? - mysql

I have a select query and I'm trying to add a join to it.
In the example below, I have a Questionentity that I use to return some results, and I want to add a join with the User entity, like:
SELECT question FROM question AS q LEFT JOIN USER u ON q.user_id= u.id;
I would like the result to be a User entity inside a Question entity, something like:
private Question (entity)
private id
private user_id
private User (entity)
private id
private name
here is my class
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Question;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
class QuestionRepository extends EntityRepository
{
/**
* #param int $currentPage
*
* #return Paginator
*/
public function getQuestions($currentPage = 1)
{
$questions = $this->createQueryBuilder('question')
->where('question.active is NULL')
->getQuery();
$paginator = $this->paginate($questions, $currentPage);
return $paginator;
}
}
I call it like this
$questionRepo = $this->container->get('doctrine')->getManager()->getRepository('AppBundle:Question');
$questions = $questionRepo->getQuestions(1);
Any ideas?

How about that:
$questions = $this->createQueryBuilder('question')
->leftJoin('question.user', 'question_user', 'WITH', 'question_user.user = :user_id')
->where('question.active is NULL')
->setParameter('user_id', $user_id)
->getQuery();
$paginator = $this->paginate($questions, $currentPage);
Edit: Because of your latest comments, i have to mention, that this suggestion is assuming that your Question entity looks like this (according User's entity:
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="question")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
If not, add this, generate entities (php app/console doctrine:generate:entities AppBundle:Question) and update DB (php app/console doctrine:schema:update --force).
PS: Before generating entities, you'll have to remove old getters/setters.

Related

Symfony4.1 Doctrine ManyToMany Reduce No of Queries

I'm working on a project. Entity are Blog,Category,Tags. Blog and Tags are in ManyToMany Relation. My repository query to fetch data by Tags filter is.
CODE1:
/**
* #return BlogPost[]
*/
public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
{
$query = $this->createQueryBuilder('p')
// ->select('p','t')
->innerJoin('p.blogTags', 't')
->where('t.slug = :val')
->setParameter('val', $value)
->orderBy('p.id', $order)
->getQuery();
$paginator = $this->paginate($query, $currentPage, $limit);
return $paginator;
}
This code works fine. All the tags(No of tags in a post)are displayed correctly. But the No of DB Query is 14. Then When I uncomment select as this,
CODE2:
/**
* #return BlogPost[]
*/
public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
{
$query = $this->createQueryBuilder('p')
->select('p','t')
->innerJoin('p.blogTags', 't')
->where('t.slug = :val')
->setParameter('val', $value)
->orderBy('p.id', $order)
->getQuery();
$paginator = $this->paginate($query, $currentPage, $limit);
return $paginator;
}
No of Query is 9. But The Tags per Post is only one(Not displaying all the tags of a single post).
To be clear info:
It displays entire list of BlogPost.
But not all Tags of a Post.
Only one Tag per Post is shown.
Question: Is code1 is correct (No of DB Query = 14) or Do I have to tweak little bit to reduce no of DB Hits. Please guide me on this.
This is the expected behaviour in both cases.
Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.
When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.
That is the reason you get more queries in this case.
Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.
When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.
To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:
$em->refresh($blogPost);
and also include refrech option on cascade operations of the relation definition:
#OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})
References:
what cascade refresh means in doctrine 2
refresh objects: different question but same solution
Thanks #Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.
BlogTags.php
/**
* #ORM\ManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
*/
private $blogPosts;
BlogPost.php
/**
* #var Collection|BlogTags[]
*
* #ORM\ManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
* #ORM\JoinTable(
* name="fz__blog_n_tag",
* joinColumns={
* #ORM\JoinColumn(name="blog_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* }
* )
* #ORM\OrderBy({"name": "ASC"})
*/
private $blogTags;
This created the join_table. Allready I have a join_table. Although This code is for reference to someone.
Controller.php
// This is my old Code
$bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
// This is my New Code
$bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
Repository.php
public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
{
$query = $this->createQueryBuilder('t')
->select('t','p','tx')
->innerJoin('t.blogPosts', 'p')
->innerJoin('p.blogTags', 'tx')
->where('p.isActive = :val1')
->andWhere('t.slug = :val2')
->setParameter('val1', true)
->setParameter('val2', $value)
->orderBy('p.id', $order)
->getQuery();
$paginator = $this->paginate($query, $currentPage, $limit);
return $paginator;
}
I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with
{% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}
Help me on this (twig file): There is only one tag, that's why |first twig filter
Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.
Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).

Doctrine findBy boolean field returns no results

Recently, a piece of code stopped working. I haven't made any changes to it so I don't know why.
Here's the code:
$invites = $this->vault_em->getRepository('AppBundle:Invite\LocalInvite')->findBy([
'active' => true,
]);
Now, it's returning an empty array, even though there are LocalInvite records with active = 1.
Here are the doctrine mappings:
/**
* #ORM\Entity
* #ORM\Table(name="invite")
*/
class LocalInvite extends Invite {
//...
}
/** #ORM\MappedSuperclass */
abstract class Invite implements \JsonSerializable {
/** #ORM\Column(type="boolean", options={"default": true}) */
protected $active;
//...
}
To debug, I copied the underlying MySQL query that Doctrine is executing from the debug logs:
SELECT t0.id AS id_1, t0.email AS email_2, t0.active AS active_3, t0.location AS location_4, t0.cohort_leadership AS cohort_leadership_5, t0.timezone AS timezone_6, t0.date_record_created AS date_record_created_7, t0.date_record_deleted AS date_record_deleted_8, t0.date_restart AS date_restart_9, t0.date_start_invite AS date_start_invite_10, t0.employee_id AS employee_id_11, t0.first_name AS first_name_12, t0.corporate_client_name AS corporate_client_name_13, t0.client_id AS client_id_14, t0.landing_page_url AS landing_page_url_15, t0.user_id AS user_id_16, t0.recipient_id AS recipient_id_17 FROM invite t0 WHERE t0.active = true;
When I plug that query into a MySQL IDE, it returns results.
Why does the findBy return no results?
try to change 'AppBundle:Invite\LocalInvite' by LocalInvite::class

Laravel migration with relation

I am new with Laravel, so I do not know what exactly is this problem. So I will describe it in detail. First I have 2 table Article and Comment, with the relation 1-1, it means that an article can only have 1 comments.
The code is:
$article = Article::with('comments')
and the result is
and below is the attribute of comment I get in relation:
But now, I want the builder select only the article where the article's content length > its comment's content length. In MySQL statement, it is
"Select from articles a where length(a.content) > (Select length(c.content) from comments c where c.article_id = a.id)
I have tried with raw and join and it work. But I want to find out that can I do the same with "with" relation? How can I do this?
Try this
$article = Article::where(DB::raw('length(content)','>' ,DB::raw('Select length(content) from comments where article_id = id'))->with(['comments'])->get();
Try this:
$articles = Article::with('comments')->get();
$onlyWithLongerContent = $articles->filter(function($article) {
return strlen($article->content) > strlen($article->comments->content);
})->values();
I will try to think of another way, but this is one way of doing it.
Another way would probably be about building queries for that using join and where clauses.
Have you tried something like this:
/**
* Get the comments.
*
* #return
*/
public function comments()
{
return $this->hasmany('App\Comments')->where('content', '!=', null);
}
Or
/**
* Get the comments
*
* #return
*/
public function comments()
{
return $this->hasManyThrough('App\Comments', 'App\Articles', 'id', 'article_id')->where('content', '!=', null);
}

Find object through chained ManyToOne relationships

I'm trying to figure out how to find a group of objects based on a layered relationship. I have 3 entities like so:
Referral --> manyToOne --> Patient --> manyToOne --> Payor
How do I find all referrals a given payor?
I'm using symfony3 with mysql and doctrine. My entities:
class Referral
{
// usual stuff
/**
* #ORM\ManyToOne(targetEntity="Patient")
*/
private $patient;
}
class Patient
{
// usual stuff
/**
* #ORM\ManyToOne(targetEntity="Payor")
*/
private $payor;
}
class Payor
{
// usual stuff
}
Obviously I could make the relationships birectional, for example so I could do something like this in my controller:
$patients = $payor->getPatients();
foreach ($patients as $patient) {
$referrals = $patient->getReferrals();
}
And then collect these into an appropriate array, but this seems messy and I'd rather do it all in a single database query in my repository. Can that be done?
you can find all referrals for a given payor using a query.
in ReferralRepository
public function findReferralsByPayor(Payor $payor)
{
$qb = $this->createQueryBuilder('r');
$qb
->join('BUNDLENAME:Patient', 'p', 'WITH', 'p.id = r.patient')
->where('p.payor = :payor')->setParameter('payor', $payor)
;
return $qb->getQuery()->getResult();
}

Doctrine2 multiple join

I have problem with my User Entity. I have code generated by Doctrine it is below:
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Frontend\UserBundle\Entity\SfGuardPermission", inversedBy="user")
* #ORM\JoinTable(name="sf_guard_user_permission",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="permission_id", referencedColumnName="id")
* }
* )
*/
protected $permission;
Problem is with join because I can't join user and permission. What I must to do? I must join sf_guard_user with sf_guard_user_group with sf_guard_grop with sf_guard_group_permission with sf_guard_permission. Because I need to get User permission. I do not no how to write join like this in code above. Is it possible?
You can not write this join in one annotation. In fact you gone have three entity tables sf_guard_user, sf_guard_group and sf_guard_permission and two cross tables which you can write as you already started, sf_guard_user_group and sf_guard_group_permission.
But since it looks like you try to migrate some symfony 1.x stuff to symfony 2.x:
The sf_guard_user_permisson table in symfony 1.x is a cross table between users and permission, containing extraordinaire permission for a user which are not granted through the groups the user is in, so you are already done.
SBH thx for replay, of course you have right with everything what you have written. But my sf_guard_user_permisson is empty so I can't use it. I can generate this table, this is no problem, but then I will must maintain it. This is next work for me so i wrote code below:
namespace Frontend\UserBundle\Entity;
// ...
/**
* #var \Doctrine\Common\Collections\Collection
*
*/
protected $permissions;
/**
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPermissions()
{
$groups = $this->getSfGuardGroups();
foreach ($groups as $group)
{
$groupPermisions = $group->getPermission();
foreach ($groupPermisions as $groupPermision)
{
if (!in_array($groupPermision, $this->permissions)) {
$this->permissions[] = $groupPermision;
}
}
}
return $this->permissions;
}
/**
* #param string $permissionName
* #return boolean
*/
public function hasPermission($permissionName)
{
$this->getPermissions();
foreach ($this->permissions as $permission)
{
if($permission->getName() === $permissionName) {
return true;
}
}
return false;
}
// ..
What do you think about it? Your opinion is very important for me.
Edit:
Thx for SBH help, I have got answer for my question. I have hope it will help other people. If you do not understand something please look at SBH answer.