include a column of pivot table on call relationships

假如想象 提交于 2019-12-13 20:22:49

问题


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');
    }

}

And in the other hand Product is like:

class Product extends Model
{
    public function price_lists()
    {
        return $this->belongsToMany(PriceList::class, 'price_lists_products', 'product_id', 'price_list_id')->withPivot('price');
    }
}

Product model has many columns like product_id ,title ,desc, created_at,active and so on.

Furthermore there is a pivot table named price_lists_products include this fields :

price_list_id
product_id
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;
    } 

That returns :

[
    {
        "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"
        }
    ]

回答1:


you could use 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;



回答2:


$prices =$price_list->products()->select('products.product_id', 'created_at')->get();


$prices  = $prices->map(function($price){

   return $price->pivot;

});

$prices->dd();

should give give you the wanted results.



来源:https://stackoverflow.com/questions/48276025/include-a-column-of-pivot-table-on-call-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!