主义2 - ManyToMany + IN子句 [英] Doctrine 2 - ManyToMany + IN clause
本文介绍了主义2 - ManyToMany + IN子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个模型:
/** @Entity @Table(name="articles") */
class Article {
/** @Id @GeneratedValue @Column(type="integer") */
protected $id;
/** @Column(type="string", length=100, nullable=true) */
protected $title;
/** @ManyToOne(targetEntity="User", inversedBy="articles") */
protected $author;
/** @Column(type="datetime") */
protected $datetime;
/**
* @ManyToMany(targetEntity="Game", inversedBy="articles")
* @JoinTable(name="articles_games",
* joinColumns={@JoinColumn(name="article_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="game_id", referencedColumnName="id")}
* )
*/
protected $games;
# Constructor
public function __construct() {
$this->datetime = new DateTime();
$this->games = new \Doctrine\Common\Collections\ArrayCollection();
}
# ID
public function getId() { return $this->id; }
# TITLE
public function setTitle($v) { $this->title = $v; }
public function getTitle() {
if(empty($this->title)) {
$game = $this->getFirstGame();
return ($game instanceof Game) ? $game->getTitle() : NULL;
} else
return $this->title;
}
# AUTHOR
public function setAuthor($v) { $this->author = $v; }
public function getAuthor() { return $this->author; }
# DATE & TIME
public function getDateTime() { return $this->datetime; }
public function setDateTime($v) { $this->datetime = $v; }
# GAMES
public function setGames($value) {
$except_txt = 'Jedna z przesłanych wartości nie jest instancją klasy Game!';
if(is_array($value)) {
foreach($value as $v) {
if($v instanceof Game) $this->games->add($v);
else throw new Exception($except_txt);
}
} else {
if($value instanceof Game) $this->games->add($value);
else throw new Exception($except_txt);
}
}
public function getGames() { return $this->games; }
}
如何使查询看起来像这样
How to make query looking like this
SELECT a FROM Article a WHERE :game_id IN a.games
我有这个( $ game-> getId()
是一个整数)
I have this (the $game->getId()
is an integer)
$articles = $db->createQuery("SELECT a.type FROM Article a WHERE :game_id IN a.games GROUP BY a.type")->setParameter('game_id', $game->getId())->getResult();
但是它给我一个语法错误
But it's returning me an syntax error
[Syntax Error] line 0, col 47: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'a'
推荐答案
如果您正在寻找与一个游戏相关的文章:
If you are looking for articles related to one game:
$articles = $db->createQuery("SELECT a FROM Article a JOIN a.games game WHERE game.id = :game_id")
->setParameter('game_id', $game->getId())
->getResult();
或多个:
$articles = $db->createQuery("SELECT a FROM Article a JOIN a.games game WHERE game.id IN (?,?, ... ?)")
->setParameters(array($game1->getId(), $game2->getId() ... $gameN->getId()))
->getResult();
这篇关于主义2 - ManyToMany + IN子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文