database - 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?非常感谢!
解决方案
您必须自己加入表格。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()
.
推荐阅读
- laravel-6 - Laravel 6:语法错误,意外的 'js' (T_STRING),期待 ')'
- c# - C#如何使用按钮添加到列表?
- c# - .NET Core 选项与 JSON 文件绑定:无效集合项的行为不一致
- android - iOS/Android - 如何在社交应用中控制用户?
- netsuite - 使用客户端脚本 2.0 创建项目收据时如何设置库存详细信息?
- android - 如何在android pie中继续运行后台服务?
- php - 使用主管或 pm2 使 laravel echo 服务器保持活动状态
- java - 如何使用 Java 中的流从两个数组中创建映射?
- java - 根据其成员的属性之一在对象列表中查找对象
- c++ - 在 Visual Studio 上创建 Google 的 CRC32C