cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How to load cart from database?

Former Member
0 Likes
973

Hi there,

I´m overriding the DefaultSessionCartService and want to implement the following:

 // this is custom code -> returns sessionCart if there is one and null if not.
   final CartModel cart = getSessionCartWithoutCreatingOne();
 
         if (null != cart) {
             return cart;
         } else if(/*cart exists in database*/){
             //load cart from database
         }else{
            //create new cart
        }

How can I check if the cart is inside the database and how can I load it then?

Cheers! Raphael

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Likes

All right.

if someone is still interrested, here is how I got it done:

    final CartModel cart = getSessionCartWithoutCreatingOne();
         if (null != cart) return cart;
 
         final CustomerModel customer = (CustomerModel) userService.getCurrentUser();
         final BaseSiteModel paramBaseSiteModel = baseSiteService.getCurrentBaseSite();
         List<CartModel> cartsForSiteAndUser = commerceCartService.getCartsForSiteAndUser(paramBaseSiteModel, customer);
 
 return cartsForSiteAndUser.isEmpty() ? cartFactory.createCart() : cartsForSiteAndUser.get(0);

hope this helps 😉

Marko_salonen
Contributor
0 Likes

Why would you call userService twice? Why not final CustomerModel currentCustomer = (CustomerModel)userService.getCurrentUser(); And if you look at getCartsForSiteAndUser method you see it takes a UserModel as argument so getCurrentUser call is enough

You should as well have the null check before you start to get the users because you then save some calls to database. And how do you handle if the user wants to have a specifc cart that it has saved? Be aware that for anonymous user this call can be heavy if the cart cleaning job has not been executed.

Former Member
0 Likes

Good point - Thanks! I dont know why I did it that way but I´ll do the refactoring and update the codesnippet tomorrow.

In this shop the user is only supposed to have one cart so thats why the ct (0) should be just fine.

Marko_salonen
Contributor
0 Likes

Refactoring is always good :)

Answers (1)

Answers (1)

andyfletcher
Active Contributor
0 Likes

I think you're looking for the method hasSessionCart() method

 if (cartService.hasSessionCart()) {
     return cartService.getSessionCart();
 }