php - Laravel 查询构建器返回空数组,尽管它不为空

标签 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 数组现在为空?

最佳答案

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

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

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

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

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

关于php - Laravel 查询构建器返回空数组,尽管它不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587913/

相关文章:

php - 在 WooCommerce 中相关产品的同一类别之前显示交叉销售

php - iOS;将图像从 UIImageView 发布到 PHP

mysql - 如何从 SQL 中的表中进行选择,其中列中的元素仅包含另一列的一个特征,而另一列本身又包含两个特征?

php - 在 zf2 中调用存储过程时发生 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 错误

php - 使用 javascript/php 将 html 表单转换为 pdf 和电子邮件

mysql - 由于语言编码,本地 mysql 导入文件 .sql 出现问题

php - 编写双连接来获取产品的子类别

php - SQLSTATE [28000] [1045] 用户 'root' 的访问被拒绝

php - 在 Laravel 中使用 php 变量发送邮件

php - Laravel ID 不匹配