在询问为什么我得到用户数据的好友的空值之后,我试图加载特定用户的好友,有人回答这是因为延迟加载。因此建议我添加JOIN,我承认这是我的怀念。但是在添加了JOIN之后,我得到了结果中朋友的数据,然后从我的users表中收到了我没有询问的所有用户。
我已经尝试从SELECT中删除myuser,但是这样我又遇到了延迟加载问题。我已经尝试过LEFT JOIN(我承认这是我旁边的愚蠢尝试)。但是,如果在查询查询语言中没有将其打开,该如何纠正呢?
我的实体(朋友):
class Friends
{
/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="myfriends")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
private $friendsWithMe;
/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="friendof")
* @ORM\JoinColumn(name="friend_id", referencedColumnName="id", nullable=false)
*/
private $afriendof;
/**
* @var integer
*
* @ORM\Column(name="status", type="smallint")
*/
private $status;
/**
* @return User
*/
public function getFriendsWithMe()
{
return $this->friendsWithMe;
}
/**
* @param mixed $friendsWithMe
*/
public function setFriendsWithMe($friendsWithMe)
{
$this->friendsWithMe = $friendsWithMe;
}
/**
* @return User
*/
public function getAfriendof()
{
return $this->afriendof;
}
/**
* @param mixed $afriendof
*/
public function setAfriendof($afriendof)
{
$this->afriendof = $afriendof;
}
/**
* @return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* @param integer $status
*/
public function setStatus($status)
{
$this->status = $status;
}
}
我的实体(用户):
class User implements UserInterface
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function __construct()
{
$this->userPosts = new ArrayCollection();
$this->myfriends = new ArrayCollection();
$this->friendof = new ArrayCollection();
}
/**
* @var
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Friends", mappedBy="afriendof")
*/
private $friendof;
/**
* @var
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Friends", mappedBy="friendsWithMe")
*/
private $myfriends;
我的存储库(FriendsRepository):
public function personalFriends($userId){
$em = $this->getEntityManager();
$result = $em->createQuery('SELECT friends, myuser FROM AppBundle\Entity\Friends friends
INNER JOIN AppBundle\Entity\User myuser WHERE friends.friendsWithMe = :userId AND friends.status = 1');
$result->setParameter('userId', $userId);
return $result->getResult();
}
我称为存储库的地方
public function indexAction(Request $request)
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$userId = $user->getId();
$friends = $this->getDoctrine()->getRepository(Friends::class)->personalFriends($userId);
dump($friends);
exit();
我现在得到的结果是: https://pastebin.com/2M4SYTLb 我期望的结果: https://pastebin.com/BxsC9QbE
答案 0 :(得分:1)
希望我了解您的问题。
但是从我看来,您在进行'SELECT friends, myuser
时要求的是朋友的数据和用户的数据。
仅尝试选择friends
赞:
SELECT friend FROM AppBundle\Entity\Friends friend INNER JOIN AppBundle\Entity\User user WHERE friend.friendsWithMe = :userId AND friend.status = 1
然后,您将只有一个Friends数组。
如果仍然存在问题,则可以添加fetch =“ EAGER”,这样就不会出现“ LAZY”
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="myfriends", fetch="EAGER")