首页 > 解决方案 > CONCAT 与 Laravel 雄辩地在表字段的两个字段之间

问题描述

我想使用 Laravel elequent 连接来自不同表的两个字段。我的架构是这样的

customers:
id
name
number

customer_types:
type
description
taxable_price

每个客户都有一个 customer_type。我想 CONCAT CUSTOMER.NAME CUSTOMER_TYPES.TYPE 作为 customer_plus_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;

那么,如何将 customers.name 和 customer_types.type CONCAT 为 customer_plus_type?非常感谢!

标签: databaselaravelpostgresqlconcat

解决方案


您必须自己加入表格。Usingwith('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().


推荐阅读