我在symfony2和doctrine2中遇到了问题。当我添加一个Criteria异常时,它并不像我想要的那样出现。这是代码:
模型
/**
* @ORM\ManyToMany(targetEntity="users",inversedBy="friends",cascade={"ALL"})
* @ORM\JoinTable(name="friends",
* joinColumns={@ORM\JoinColumn(name="friend_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* )
*/
private $friendsof;
public function getusersre() {
$criteria = new Criteria();
$criteria->Where($criteria->expr()->eq('accepted', '1'));
return $this->friendsof->matching($criteria);
}
输出
SELECT te.id AS id, te.email AS email, te.username AS username
FROM users te JOIN friends t ON t.user_id = te.id
WHERE t.friend_id = ? AND te.accepted = ?
我希望它看起来像这样:
WHERE t.friend_id = ? AND t.accepted = ?
答案 0 :(得分:0)
Doctrine为Many to Many
关系生成中间表。而且您无法向该表添加任何字段。我指的是accepted
字段。你还有三张桌子:
在getusersre
功能中,您想尝试吸引朋友。据我所知,无法根据需要为您的条件添加accepted
字段。
我也改变了你的结构。你觉得怎么样?
class User
{
/**
* @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=255, unique=true)
*/
private $username;
/**
* @ORM\OneToMany(targetEntity="Friend", mappedBy="userId")
*/
private $friends;
//Other fields, getters and setters.
}
class Friend
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $userId;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
* @ORM\JoinColumn(name="friend_id", referencedColumnName="id")
*/
protected $friendId;
/**
* @ORM\Column(name="accepted", type="boolean")
*/
protected $accepted;
//Other fields, getters and setters
}
Friend
实体的名称并不牢固。您可以使用FriendRelationship
。
此外,函数getAcceptedFriends
会喜欢这样。
public function getAcceptedFriends()
{
$cr = Criteria::create();
$cr->andWhere($cr->expr()->eq('accepted', 1));
return $this->friends->matching($cr);
}
或
public function getAcceptedFriends()
{
$friends = [];
/** @var Friend $friend */
foreach ($this->friends as $friend) {
if ($friend->getAccepted()) $friends[] = $friend;
}
return $friends;
}
你可以这样使用。
foreach($user->getAcceptedFriends() in $friendRelationship){
// $friendRelationship is a instance of Friend.
$username = $friendRelationship->getFriendId()->getUsername();
}
在树枝上
{% for fr in user.acceptedFriends %}
{{ fr.friendId.username }}
{% else %}
{{ 'No friend' }}
{% endfor %}