include a column of pivot table on call relationships

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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;

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x