[英]How to pass array into the where condition?
我有動態 where 條件。 它們由以下數組組成:
array:2 [
"brand_name" => array:2 [
0 => "a"
1 => "b"
]
"category_type" => array:1 [
0 => "AA"
]
]
我需要將 where 條件應用於我的查詢。
$em = $this->getEntityManager();
$sql = " select * from products as p";
$i = 0;
foreach ($wheres as $key => $value) {
if ($i === 0) {
$sql .= " WHERE";
} else {
$sql .= " AND";
}
$sql.= " te.$key IN (:$key)";
$i +=1;
}
我不確定如何將值分配給查詢。 如果我有單一的 where 條件,我會這樣做:
$params = array(
$ids,
);
$query = $em->getConnection()->executeQuery(
$sql,
$params,
array(
\Doctrine\DBAL\Connection::PARAM_STR_ARRAY,
\PDO::PARAM_INT,
)
);
$records = $query->fetchAll();
但我不知道如何解決動態條件的位置。
這很容易使用查詢生成器。 這是它的設計目的。
像這樣的東西會帶你去那里:
$qb = $this->createQueryBuilder('p');
$suffix = 0;
foreach ($conditions as $key => $value) {
$parameter = 'query_' . $suffix++;
$qb->andWhere("p.$key IN :$parameter")
->setParamter($parameter, $value);
}
$records = $qb->getQuery()->getResult()
您需要進行調整以適應您的數據 model。 在您的問題中,您選擇products as p
,但隨后您嘗試 select 來自te
,所以我想拼圖中缺少一些部分。
但是你應該可以從這里完成它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.