Database 从表字段开始,两个字段之间的CONCAT和Laravel雄辩

Database 从表字段开始,两个字段之间的CONCAT和Laravel雄辩,database,laravel,postgresql,concat,Database,Laravel,Postgresql,Concat,我想使用Laravel elequent从不同的表中合并两个字段。我的模式是这样的 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,

我想使用Laravel elequent从不同的表中合并两个字段。我的模式是这样的

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;
那么,如何将customers.name和customer\u types.type定义为customer\u plus\u type?
多谢

您必须自己加入表格。与('other_table')一起使用
只会加载相关模型,而不会在一个查询中加载。通过()传递到
的每个引用模型将产生一个附加查询

在您的情况下,解决方案可能如下所示:

$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\u plus\u type
的自定义字段。请确保相应地更改
加入
中的
客户.客户类型\u id
字段。从你的问题来看,不清楚它是如何命名的


顺便说一下,如果您仍然需要急于加载
customerType
关系,您可以在调用
first()

之前的某个地方添加
with('customerType')
,您需要数据库中带有
concat
的解决方案,还是PHP代码中的解决方案可以接受,
customers.name
的表名中有一个输入错误。我必须使用CONCAT。那么需要做什么呢?我可以在同一个表字段中进行操作,但“与”表的关系是什么。请更清楚地说明发生了什么。你发布了一堆代码,但没有解释发生了什么。有错误信息吗?连接不起作用?字段没有出现吗?如果你不解释这一点,就很难帮助你