dqxhit3376 2015-09-05 18:41
浏览 511
已采纳

在第二个参数中使用DB :: raw()时的不同值where()

I have next query in Laravel Eloquent:

$buildings = Building::select('buildings.*')->join(
    DB::raw('('.
        (
            IngameBuilding::select('buildings.building_id', 'buildings.level')
                          ->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
                          ->toSql()
        ).
    ') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
    ->where('buildings.level', '>', 'added_buildings.level')
    ->get();

This query returns all allowed rows from base, but one row more. When I added DB::raw() in where() return values is valid.

Good-working code:

$buildings = Building::select('buildings.*')->join(
    DB::raw('('.
        (
          IngameBuilding::select('buildings.building_id', 'buildings.level')
                        ->join('buildings', 'buildings.id', '=', 'ingame_buildings.building_id')
                        ->toSql()
        ).
    ') as `added_buildings`'), 'added_buildings.building_id', '=', 'buildings.building_id')
    ->where('buildings.level', '>', DB::raw('`added_buildings`.`level`'))
    ->get();

Why first code workig, hmm.. Wrong?

  • 写回答

1条回答 默认 最新

  • dougu4027 2015-09-05 18:55
    关注

    I'm not a big fan of Laravel at all. I've got only small experience with this framework but i'm almost sure that where function accepts only a 'constant' values to be checked against.

    If you'll get an output of this query using toSQL method on the query object you will see that eloquent will convert it as something like:

    (...) where buildings.level > 'added_buildings.level'
    

    so the condition checks if the buildings.level (whatever the type is) is greater than the given string and not the column value.

    Using the DB::raw you're getting the proper sql as the eloquent won't parse/convert it.

    You would need to use whereRaw method I suppose. http://laravel.com/docs/4.2/queries#introduction

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码