2

I have a problem, I am trying to retrieve orders with products from my database. The idea is that you have an order with products in it and a product can have options with different options. For example a big mac menu has different options, such as size with three different options. This is what I have now:

OrderModel:

class Order extends Model
{
    use HasFactory;
    protected $table = 'orders';

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function table()
    {
        return $this->belongsTo(Table::class);
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('quantity');
    }


}

OrderProduct:

class OrderProduct extends Pivot
{
    use HasFactory;
    public $incrementing = true;
    protected $table = 'order_product';

    public function options()
    {
        return $this->hasMany(OrderProductOptions::class);
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }
}

OrderProductOptions:

class OrderProductOptions extends Model
{
    use HasFactory;
    public $incrementing = true;
    protected $table = 'order_product_options';

    public function options()
    {
        return $this->belongsTo(OrderProductsOptionsOptions::class);
    }
}

OrderProductsOptionsOptions:

class OrderProductsOptionsOptions extends Model
{
    use HasFactory;
    protected $table = 'order_products_options_options';

    public function Option()
    {
        return $this->belongsTo(OrderProductOptions::class);
    }

}

enter image description here

When I want to pick up an order with products and selected options like this:

$newOrder = Order::with('products.options')->findOrFail($order->id);

I get all the options that the product has, how do I get only the selected ones that belong to the order?

1 Answer 1

1

see laravel document , you must define foringPivotKey and relatedPivot key like this:

return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.