cannect
2 weeks ago

Pivot ->using() not working as expected

Posted 2 weeks ago by cannect

Hi all,

I have a Order model with a pivoted relationship for the ordered products:

class Order extends Model
{

    public function products()
    {
        return $this->belongsToMany( Product::class )
                    ->using( OrderProduct::class )
                    ->withPivot('price' ); // ommitted the rest for clarity
    }

    // subtotal of all OrderProduct's
    public function subtotal()
    	$this->products->map->price->sum(); // <-- this returns that price is not found on the *Product* model
    }
}

OrderProduct model

class OrderProduct extends Pivot
{

    // has property price
}

Product model

class Product extends Model
{

   
}

What I want to accomplish is that $this->products returns a collection of OrderProducts.

Because I used ->using( OrderProduct::class ) I expected this to work.

My question is, should $this->products return a collection of Products, or OrderProducts? I expected a collection of OrderProducts, but got Products.

Edit: strangely, if I edit the Order model relation like this:

class Order extends Model
{

    public function products()
    {
        return $this->belongsToMany( Product::class )
                    ->using( OrderProduct::class )
		    ->as( 'orderproducts' ) // added
                    ->withPivot('price' ); 
    }
}

Then $this->products->map->orderproducts returns the result I want. I can't belive I read both the ->as() and the ->using() function wrong in the docs?

Please sign in or create an account to participate in this conversation.