Laravel Query构建器返回空数组,尽管它不是null

时间:2015-07-23 12:50:51

标签: php mysql laravel

基于此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数组现在为空?

1 个答案:

答案 0 :(得分:4)

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

如果要使用表达式,请使用raw()包裹它:

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

或直接使用whereRaw()方法:

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