【问题标题】:appending ->where() clauses based on conditionals根据条件附加 ->where() 子句
【发布时间】:2016-11-25 16:49:00
【问题描述】:

我想根据某些条件将where 子句附加到查询中,问题是我检查它是否从数据库返回一行的方式总是返回true。

如果我像这样在一行中进行查询:

$test= DB::table('users')->where('email', $email)->where('password', $password)->first();

它按预期工作,如果找到一行它是真的,反之亦然,但如果我像这样附加到查询中,它总是正确的(这是有道理的,但我如何检查它是否真的从数据库?):

$test= DB::table('users');
$test->where('email', $email);
 $test->where('password', $password);
$test->first();

if ($test) {
       // always true
 }

【问题讨论】:

  • $test 为空的情况下究竟包含什么?
  • @Don'tPanic 不错!

标签: php mysql laravel-5 fluent


【解决方案1】:

语句$test->first(); 执行查询并返回第一个结果,但您没有将该结果分配给任何东西,所以$test 仍然只是查询对象,它总是会像您一样评估为true看到。如果你将它分配给其他东西然后检查它,它应该可以工作。

$example = $test->first();

if ($example) { ...

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2016-12-16
    • 2021-04-09
    相关资源
    最近更新 更多