代码之家  ›  专栏  ›  技术社区  ›  Nazmus Shakib

在表字段的两个字段之间用Laravel雄辩地连接

  •  -1
  • Nazmus Shakib  · 技术社区  · 7 年前

    customers:
    id
    name
    number
    
    customer_types:
    type
    description
    taxable_price
    

    每个客户都有一个客户类型。我要将CUSTOMER.NAME CUSTOMER\u TYPES.TYPE合并为CUSTOMER\u plus\u TYPE:

    Desire Output:
    
        {
          "name": CUSTOMER_NAME,
          "customer_plus_type": CUSTOMER_NAME - TYPEs,
          "customer_type": {
             "customer_plus_type": CUSTOMER_NAME - TYPEs
           }
        }
    

    我已经在倒霉的日子里试过了。

    $customers = Customer::with(['customerType'=> function($q) {
                $q->select(['id',
                    DB::raw("CONCAT(custmers.name,' - ',customer_types.type)  AS customer_plus_type")
                ]);
        }])->first();
    
        return $customers;
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   Namoshek    7 年前

    你得自己加入这些表格。使用 with('other_table') 只加载相关模型,但不在一个查询中加载。传递给的每个引用模型 with() 将产生一个附加查询。

    $customer = Customer::query()
        ->join('customer_types', 'customers.customer_type_id', '=', 'customer_types.id')
        ->select([
            'customers.*',
            DB::raw("CONCAT(customers.name, ' - ', customer_types.type) as customer_plus_type"),
        ])
        ->first();
    

    这将选择 customers customer_plus_type . 请一定要换衣服 customers.customer_type_id join 相应地。从你的问题看不清楚它是怎么命名的。

    顺便说一下,如果您还需要加载 customerType 关系,你可以加上 with('customerType') 在打电话之前的某个地方 first() .