我正在編寫下面列出的代碼,根據各種值動態生成查詢過濾器腳本。在某些情況下,這些值很少,但在某些情況下,它超出了極限,這看起來我的代碼結構非常令人費解。以有效方式生成動態SQL過濾器腳本
以下是樣本過濾器查詢生成代碼。
if ($entity->iscomments != 2)
{
$script .= " v.iscomments=:iscomments";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isprivate != 3 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->filter > 0 || $entity->mode > 0 || $entity->galleryid > 0)
$script .= " AND";
}
if ($entity->galleryid > 0)
{
$script .= " v.galleryid=:galleryid";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isprivate != 3 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->mode > 0)
$script .= " AND";
}
if ($entity->isprivate != 3)
{
$script .= " v.isprivate=:isprivate";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->mode > 0)
$script .= " AND";
}
if ($entity->mode > 0)
{
$script .= " v.mode=:mode";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0)
$script .= " AND";
}
if ($entity->categoryid != 0)
{
$script .= " v.categoryid=:categoryid";
if ($entity->term != "" || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0)
$script .= " AND";
}
在代碼它看起來像如果沒有巨大的條件,這使得代碼conjested,而不是很好看,但它完美。
有沒有更好的方法來處理這種情況,以便生成複雜的過濾器查詢,但使用更少的代碼量和更好的方法。
我不明白內大if語句。不應該總是有'AND',但不是在查詢結束時? – bitWorking
如果條件檢查內部是否存在其他過濾器活動,如果是,那麼它附加AND之前。 – irfanmcsd
另一種方法http://stackoverflow.com/questions/14351617/build-dynamic-sql-with-and-expressions-without-confusing-nested-conditionals/14351748#14351748 – goat