似乎无法弄清楚这里有什么问题,因为我的实体似乎有正确的注释等。转换SQL直接在Navicat中运行它可以工作。
具体错误是
[Semantical Error] line 0, col 120 near 'city_id = 2)': Error: Class Simpleweb\Entity\Product has no field or association named city_id
与city_id相关的产品实体部分(City是OneToMany相关实体)
/**
* @ManyToOne(targetEntity="City", inversedBy="products")
* @JoinColumn(name="city_id", referencedColumnName="id")
**/
private $city;
控制器中的代码正在尝试根据用户选择的多个过滤器构建动态查询。与此相关的一个尝试将城市ID号添加到where子句:
public function findByPhrases($phrase, $sortBy = null, $cityFilter = null){
$searchWords = $this->phraseToWords($phrase);
$result = null;
if(!is_null($searchWords)){
/*
* Build query, e.g. below:
*
* SELECT * FROM products
* WHERE description_short
* (LIKE '%sander%' OR name LIKE '%sander%') AND
* (city_id = 1 OR city_id = 3)
*/
try{
$sql = "SELECT p FROM Simpleweb\Entity\Product p WHERE ";
// Append an OR where clause onto the end for each word
$sql .= "(";
foreach($searchWords as $word){
$sql .= "(p.description_short LIKE '%$word%') OR (p.name LIKE '%$word%') OR ";
}
$sql = substr($sql, 0, -4); // Remove the last 'OR' from the end of the SQL statement
$sql .= ")";
if($cityFilter != null){
$sql .= " AND (";
foreach($cityFilter as $city){
$sql .= "p.city_id = $city OR ";
}
$sql = substr($sql, 0, -4);
$sql .= ")";
}
// Add sorting statement
if(strlen($sortBy) >= 1){
switch($sortBy){
case 'dateadded':
$sql .= " ORDER BY p.created ASC";
break;
case 'priceasc':
$sql .= " ORDER BY p.totalprice ASC";
break;
default:
break;
}
}
echo($sql);
$em = $this->getEntityManager();
$qb = $em->createQuery($sql);
$result = $qb->getResult();
}catch(Exception $ex){
echo($ex->getMessage());
}
return $result;
}else{
return null;
}
}
答案 0 :(得分:0)
好的,整理出来:
$sql = "SELECT p FROM Simpleweb\Entity\Product p WHERE ";
更改为
$sql = "SELECT p FROM Simpleweb\Entity\Product p JOIN p.city c WHERE ";
和
$sql .= "p.city_id = $city OR ";
更改为
$sql .= "c.id = $city OR ";