在来自 table 字段的两个字段之间使用 Laravel eloquent CONCAT
CONCAT with Laravel eloquent between two fields from table field
我想使用 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 连接为 customer_plus_type?
非常感谢!
您必须自己加入 table。使用 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();
这将 select customers
table 的所有字段以及名称为 customer_plus_type
的自定义字段。请确保相应地更改 join
中的 customers.customer_type_id
字段。根据您的问题,不清楚它是如何命名的。
顺便说一句,如果您仍然需要预先加载 customerType
关系,您可以在调用 first()
.
之前的某处添加 with('customerType')
我想使用 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 连接为 customer_plus_type? 非常感谢!
您必须自己加入 table。使用 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();
这将 select customers
table 的所有字段以及名称为 customer_plus_type
的自定义字段。请确保相应地更改 join
中的 customers.customer_type_id
字段。根据您的问题,不清楚它是如何命名的。
顺便说一句,如果您仍然需要预先加载 customerType
关系,您可以在调用 first()
.
with('customerType')