代码之家  ›  专栏  ›  技术社区  ›  HexaCrop

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

  •  1
  • HexaCrop  · 技术社区  · 7 年前

    $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
    ];
    

    我的 custom_config

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

    我的 car_service_fee 正在获取 8.5

    但是我的 bike_service_fee 他回来了 null first()

    同样的代码也适用于如下所示的情况,

    $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
    ];
    

    背靠背有什么问题吗 第一()

    谢谢你

    2 回复  |  直到 7 年前
        1
  •  5
  •   lagbox    7 年前

    $config 是查询生成器对象。您对此对象进行的大多数调用都是“构建”查询。物体保存了所有这些 where 内部条件。当调用执行查询的方法时,它将编译查询,执行查询并返回结果[调用 first get 或者……]。构建器本身仍然作为一个构建器存在,可以继续构建,或者可以再次执行查询,等等。

    在您的情况下,您正在添加更多 哪里 此查询对象的条件, ,每次你打电话 哪里 在上面。

    toSql 以查看生成的查询的外观。

    可以通过创建新的生成器对象或克隆来避免这种情况 $配置 因此,可以生成两个单独的查询。

    例子:

    $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
    ];
    

    $config2 两个都有第一个 哪里 条件。

    如果事后不需要这些构建器,您也可以在线克隆它们:

    'car_service_fee' => (clone $config)->where(...)->first()->...,
    'bike_service_fee' => (clone $config)->where(...)->first()->...,
    
        2
  •  0
  •   Tharaka Dilshan    7 年前

    每次你打电话 where() $config 对象在其上创建新副本,然后调用函数

    $cost = [
         'car_service_fee' => (clone $config)->where('managed_by', 1)->first()->service_fee,
         'bike_service_fee' => (clone $config)->where('managed_by', 2)->first()->service_fee
    ];
    
    推荐文章