Doctrine many to many: has user liked the article?

荒凉一梦 提交于 2020-01-16 19:48:22

问题


I have 2 Entities

User Article and a “likedByUsers” Many To Many relationship between both.

When I show an article, I want to know if the user has liked it so a heart icon is shown.

I've got this in the ArticleRepository:

public function findOneBySlug($slug,$userId): ?Pack
{
    return $this->createQueryBuilder('p')
        ->andWhere('p.slug = :val')
        ->setParameter('val', $slug)
        ->addSelect('COUNT(u) AS userLike', 'p')
        ->leftJoin("p.users", 'u', 'WITH', 'u.id = :userId')
        ->setParameter('userId', $userId)
        ->getQuery()
        ->getOneOrNullResult()
    ;
}

But it throws an error:

Return value of App\Repository\ArticleRepository::findOneBySlug() must be an instance of App\Entity\Article or null, array returned

I want to add "userLike" (bool) to the Article returned entity. Anyone can help me out?


回答1:


calling addSelect(...) on a query builder might change the return type / format.

in your particular case, the former db result was something like [... all the article properties ...] which hydration and the getOneOrNullResult turns into one Article or null.

the new format looks like

[... all the article properties ..., userlike], which hydration turns into [Article, userlike] which can't possibly turned into one Article or a null result, because it's a "more complex" array.

So you have to use a different result fetcher. Depending on what the caller of your function expects as a return value (I would expect an article ^^) you maybe should rename the function or add a virtual property on article to hide the userlike or something, so you can return just the Article or null.

So the solution that I would choose:

$result = $this->createQueryBuilder(...)
   //...
   ->getSingleResult();
if(!$result) { 
    // empty result, obviously
    return $result; 
}
// $result[0] is usually the object.
$result[0]->userLike = $result['userLike']; 
// or $result[0]->setUserLike($result['userLike'])

return $result[0];

btw: $this->createQueryBuilder($alias) in a repository automatically calls ->select($alias), so you don't have to addSelect('... userLike', 'p') and just do addSelect('... userLike')



来源:https://stackoverflow.com/questions/57687955/doctrine-many-to-many-has-user-liked-the-article

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!