dp518158 2018-10-03 21:24
浏览 103
已采纳

Laravel:在查询构建器上背靠背使用first()时出错

I have the following code in my laravel project

$config = DB::table('custom_config')->where('item_id', 5);
$cost = [
    'car_service_fee' => $config->where('managed_by', 1)->first()->service_fee,
    'bike_service_fee' => $config->where('managed_by', 2)->first()->service_fee
];

My custom_config table is as of below.

+---------+------------+-------------+
| item_id | managed_by | service_fee |
|---------+------------+-------------|
|    5    |       1    |    8.5      |
|---------+------------+-------------|
|    5    |       2    |    2.0      |
+---------+------------+-------------+

my car_service_fee is fetching the result of 8.5

but my bike_service_fee is returning null on first()

The same code works if it is just like given below,

$cost = [
    'car_service_fee' => DB::table('custom_config')->where('item_id', 5)->where('managed_by', 1)->first()->service_fee,
    'bike_service_fee' => DB::table('custom_config')->where('item_id', 5)->where('managed_by', 2)->first()->service_fee
];

Is there any problem on back to back first() method used on a query builder that is stored in a variable or something in laravel?

Thank you

  • 写回答

2条回答 默认 最新

  • dongtan7201 2018-10-03 21:43
    关注

    $config is a Query Builder object. The majority of calls you are making on this object are 'building' a query. The object keeps all these where conditions internally. When a method to execute the query is called it will compile the query, execute it and return a result [calling first or get or ...]. The builder itself still exists as a builder and can continue to be built upon or the query can be executed again, etc.

    In your case you are adding more where conditions to this single query object, $config, every time you call where on it.

    You can see this behavior at any time by calling toSql on a builder to see what the generated query would look like.

    You can avoid this by creating a new builder object or cloning $config so you can have 2 separate queries being built.

    Example:

    $config = DB::table('custom_config')->where('item_id', 5);
    $config2 = clone $config;
    
    $cost = [
         'car_service_fee' => $config->where('managed_by', 1)->first()->service_fee,
         'bike_service_fee' => $config2->where('managed_by', 2)->first()->service_fee
    ];
    

    $config and $config2 both have the first where condition.

    You could just clone them inline as well, if you don't need these builders after the fact:

    'car_service_fee' => (clone $config)->where(...)->first()->...,
    'bike_service_fee' => (clone $config)->where(...)->first()->...,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部