在呼叫关系上包括数据透视表的列 [英] include a column of pivot table on call relationships
本文介绍了在呼叫关系上包括数据透视表的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个像这样的PriceList
模型:
Suppose we have a PriceList
model like this:
class PriceList extends Model
{
protected $primaryKey = 'price_list_id';
public function products()
{
return $this->belongsToMany(Product::class, 'price_lists_products', 'price_list_id', 'product_id')->withPivot('price');
}
}
另一方面,Product
就像:
class Product extends Model
{
public function price_lists()
{
return $this->belongsToMany(PriceList::class, 'price_lists_products', 'product_id', 'price_list_id')->withPivot('price');
}
}
产品模型具有许多列,例如product_id
,title
,desc
,created_at
,active
等.
Product model has many columns like product_id
,title
,desc
, created_at
,active
and so on.
此外,还有一个名为price_lists_products
的数据透视表,其中包括以下字段:
Furthermore there is a pivot table named price_lists_products
include this fields :
price_list_id
product_id
price
现在,我想选择附加到特定价格表的所有产品,但只获取一些选定的列以及数据透视表中的price
列.为此,我写道:
Now I want to select all products attached to a specific price list but only fetch some selected columns along with price
column in pivot table. for that I wrote :
public function prices(Request $request, PriceList $price_list)
{
$prices =
$price_list->products()->select('products.product_id', 'created_at')->get();
return $prices;
}
返回:
[
{
"product_id": 1,
"created_at": "2017-12-11 12:21:49",
"pivot": {
"price_list_id": 1,
"product_id": 1,
"price": "3000.00"
}
},
{
"product_id": 2,
"created_at": "2017-12-14 07:52:22",
"pivot": {
"price_list_id": 1,
"product_id": 2,
"price": "6000.00"
}
}
]
但是我希望结果采用以下格式:
But I want result be in this format :
[
{
"product_id": 1,
"created_at": "2017-12-11 12:21:49",
"price": "3000.00"
},
{
"product_id": 2,
"created_at": "2017-12-14 07:52:22",
"price": "6000.00"
}
]
推荐答案
您可以使用map()
.
$prices = $price_list->products()->select('products.product_id', 'created_at')->get();
$prices = $prices->map(function($item) {
$item->price = $item->pivot->price;
return $item;
});
return $prices;
这篇关于在呼叫关系上包括数据透视表的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文