原则:如何才能在查询中仅在必要时才包含 where 子句?

发布于 2024-09-30 23:47:58 字数 373 浏览 3 评论 0原文

我想使用单个查询来检索:

  • 任何类别的项目(未应用过滤器);
  • 仅单个类别的项目(仅限于特定类别);

为此,我应该能够编写一个 Doctrine 查询,仅当满足特定条件(例如,部分 URL 存在)时才包含 where 子句,否则,where 子句不包含在查询中。

当然,我尝试使用 If 语句,但由于学说查询是链接的,因此会引发错误。

所以我想解决方案可能是某种(对我来说未知的)以非链接形式编写学说查询的方法(不让每一行以“->”开头,并且查询的每一行都以分号“;”结尾)

我想这样就可以使用 IF 语句。

或者,也许这个问题已经有一些非常简单的解决方案?

感谢您的回复!

I want to use a single query to retrieve:

  • items of any categories (no filter applied);
  • only items of a single category (limited to a particular category);

For that purpose I should be able to write a Doctrine query which would include a where clause only when certain condition is met (eg. part of URL existing), otherwise, where clause is not included in the query.

Of course, i tried with using the If statement, but since doctrine query is chained, the error is thrown.

So i guess the solution might be some (to me unknown) way of writing doctrine queries in an unchained form (by not having each row started with "->" and also having each row of a query ending with semicolon ";")

That way the usage of IF statement would be possible i guess.

Or, maybe there's already some extremely simple solution to this matter?

Thanks for your reply!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拧巴小姐 2024-10-07 23:47:58

我不熟悉 Codeigniter 但你不能写这样的东西吗?

$q = Doctrine_Query::create()
    ->from('items');

if ($cat)
    $q->where('category = ?', $cat);

I am unfamiliar with Codeigniter but can't you write something like this?

$q = Doctrine_Query::create()
    ->from('items');

if ($cat)
    $q->where('category = ?', $cat);
与酒说心事 2024-10-07 23:47:58

在您的模型中,将 where 的条件作为函数中的参数传递。
在下面的示例中,我假设函数名称为 filter_query() 并将 where 条件作为参数传递。

function filter_query($condition=''){

$this->db->select('*');
$this->db->from('TABLE NAME');
   if($condition != ''){
    $this->db->where('condition',$condition);
   }
}

在上面的示例中,我使用了 Codeigniter 的 Active Record 类

In your model pass the condition for where as a parameter in a function.
In below example i am assuming the function name to be filter_query() and passing where condition as a parameter.

function filter_query($condition=''){

$this->db->select('*');
$this->db->from('TABLE NAME');
   if($condition != ''){
    $this->db->where('condition',$condition);
   }
}

In above example i have used Codeigniter's Active Record Class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文