【发布时间】: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 列)?