【问题标题】:Laravel Query builder returns empty array despite it being not nullLaravel 查询构建器返回空数组,尽管它不为空
【发布时间】:2015-07-23 12:50:51
【问题描述】:

基于这篇http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ 文章

select * from nested_category
+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          | 1   | 20  |
|           2 | TELEVISIONS          | 2   | 9   |
|           3 | TUBE                 | 3   | 4   |
|           4 | LCD                  | 5   | 6   |
|           5 | PLASMA               | 7   | 8   |
|           6 | PORTABLE ELECTRONICS | 10  | 19  |
|           7 | MP3 PLAYERS          | 11  | 14  |
|           8 | FLASH                | 12  | 13  |
|           9 | CD PLAYERS           | 15  | 16  |
|          10 | 2 WAY RADIOS         | 17  | 18  |
+-------------+----------------------+-----+-----+
10 rows in set (0.00 sec)

使用 Laravel 并使用如下原始查询:

$leaf_nodes = DB::select( DB::raw("SELECT name FROM nested_category WHERE rgt = lft + 1") );
print_r(DB::getQueryLog());
var_dump($leaf_nodes);

在我的浏览器中,我得到了预期的结果,即

Array ( [0] => Array ( [query] => Illuminate\Database\Query\Expression Object ( [value:protected] => SELECT name FROM nested_category WHERE rgt = lft + 1 ) [bindings] => Array ( ) [time] => 1 ) )
array (size=6)
 0 => 
  object(stdClass)[177]
  public 'name' => string 'TUBE' (length=4)
 1 => 
  object(stdClass)[178]
  public 'name' => string 'LCD' (length=3)
 2 => 
  object(stdClass)[179]
  public 'name' => string 'PLASMA' (length=6)
 3 => 
  object(stdClass)[180]
  public 'name' => string 'FLASH' (length=5)
 4 => 
  object(stdClass)[181]
  public 'name' => string 'CD PLAYERS' (length=10)
 5 => 
  object(stdClass)[182]
   public 'name' => string '2 WAY RADIOS' (length=12)

为什么使用查询生成器无法正常工作?

$leaf_nodes = DB::table('nested_category')
                ->select('name')
                ->where('rgt', '=', 'lft + 1')
                ->get();    
print_r(DB::getQueryLog());
var_dump($leaf_nodes);

返回浏览器:

Array ( [0] => Array ( [query] => select `name` from `nested_category` where `rgt` = ? [bindings] => Array ( [0] => lft + 1 ) [time] => 1 ) )
array (size=0)
  empty

$leaf_nodes 数组现在为空?

【问题讨论】:

  • 也许“lft + 1”被解释为一个字符串,而不是它应该是的操作。您是否尝试将列名放在重音符号之间(如 rgt 列)?

标签: php mysql laravel


【解决方案1】:

因为where() 方法认为您正在传递一个字符串以与列值进行比较(它失败了,因为它将rgt 列值与字符串“lft +1”,文字进行了比较)。

如果你想使用表达式,用 raw() 包裹它:

->where('rgt', '=', \DB::raw('lft + 1'))

或者直接使用whereRaw()方法:

->whereRaw('rgt = lft + 1')

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-09-07
    • 2021-07-13
    • 1970-01-01
    • 2016-03-24
    相关资源
    最近更新 更多