I like to call it “Guest Checkout Remorse.” It’s that moment when a customer finishes checking out as a guest, only to realize that this means they cannot log-in to the website to check their order status. So they promptly create an account and then contact customer service to ask if their previous guest order can be linked to their new customer account.

Isn’t customer service wonderful?

While Magento does not provide a way to do this through the admin panel, it’s relatively easy using a couple SQL queries. Simply log in to the MySQL panel of your choice (phpMyAdmin and Adminer are two great options), and execute the following queries:

UPDATE sales_flat_order SET customer_id = (YOUR-CUSTOMER-ID), customer_is_guest=0 WHERE entity_id = YOUR-ORDER-ID AND customer_id IS NULL UPDATE sales_flat_order_grid SET customer_id = YOUR-CUSTOMER-ID WHERE entity_id = YOUR-ORDER-ID AND customer_id IS NULL

Wondering how to get the right values for customer_id and entity_id? It’s easy. To get the customer_id simply go to Customers > Manage Customers in the Magento admin. Find the customer you’re looking up and click on them as if you’re going to edit their information. When you’re viewing the customer info, the tail end of your URL will look something like this:

/index.php/admin/customer/edit/id/3193/

In this example, the customer_id is 3193. In order to find the entity_id of the order that was placed using guest checkout, go to Sales > Orders in the Magento admin panel and click on the order to view the details. Look at the tail end of the URL again:

/index.php/admin/sales_order/view/order_id/16675/

In this example, the entity_id for the order is 16675. Use your values in the SQL query statements shown above and you’ll be all set. You can double-check that the association has been made by going to Customers > Manage Customers in the Magento admin, looking up the customer in question, and you should see the order is now part of their order history.

H/T Fran and R.S at Stack Overflow . Copied and expanded here for my reference.

Published by

Brian Lyman

Brian is the founder of Vale Studios, which is really just a stage name for what has been a great experience in freelancing. Brian is currently working under a dedicated contract for a terrific e-commerce retailer, but he uses this space to continue publishing ideas and reflections related to e-commerce, marketing, and Magento.

Взяв Zend_ACL в качестве примера, мне интересно, как это должно быть организовано для проекта. Конечно, пример хорош и аккуратен, но реальный сайт намного сложнее.

$ = new Zend_Acl(); $acl->addRole(new Zend_Acl_Role("guest")); $acl->addRole(new Zend_Acl_Role("member")); $acl->addRole(new Zend_Acl_Role("admin")); $parents = array("guest", "member", "admin"); $acl->addRole(new Zend_Acl_Role("someUser"), $parents); $acl->add(new Zend_Acl_Resource("someResource")); $acl->deny("guest", "someResource"); $acl->allow("member", "someResource"); echo ($acl->isAllowed("guest", "someResource") ? "allowed" : "denied");

Учитывая, что каждый контроллер / страница на моем сайте будет иметь какую-то проверку доступа, мне нужны правила, доступные во всем мире. Означает ли это, что мне нужно создать массивный файл конфигурации или класс для настройки всех правил загрузки? Разве это не потеряло бы много памяти?

Но если я только установил правила, необходимые для каждого контроллера, который бы превзошел цель ACL? Основная причина использования ACL заключается в том, чтобы избежать распространения разрешений по всей кодовой базе:

Admin_Controller { public function action() { if($user->role !== "admin") { die("not allowed"); } } }

Как насчет изменений? Что делать, если правила ACL хранятся в базе данных, где администратор может легко изменять разрешения. Должны ли все они загружаться каждый запрос страницы? Разве это не положило бы большую нагрузку на систему?

Короче говоря, как ACL работает на большом сайте? Какие проблемы возникают? Как обрабатываются каскадные разрешения?

Вы можете хранить роли в базе данных и кэшировать объект в памяти с помощью memcache, так что вам нужно будет только запрашивать db при добавлении или изменении новых ролей. Что касается реализации ACL, так как он будет использоваться в рамках всей системы, вы можете инициализировать его в файле Bootstrap.php, а затем сохранить объект в Zend_Registry, чтобы он был доступен для всего вашего приложения.

Применение этих правил может происходить в разных точках. Вы можете использовать маршруты в настраиваемом маршрутизаторе или, возможно, на более высоком уровне на уровне контроллера. Если вы расширите Zend_Controller_Action, вы можете поместить свои правила ACL в этот главный контроллер, из которого выведен любой другой контроллер. Вы можете проверить разрешения ACL в методе _init (). Там могут быть другие точки в системе, в которых вам нужен ACL, или хотите проверить его, в зависимости от того, как и как вы его создаете (поэтому вы храните ACL в реестре).

It’s going to happen when you run an E-Commerce website – a user who has an account checkouts while is a guest, contacts you and wants the two to be associated. Yeah, extra work for you!

In Magento, there isn’t a default feature that allows you to associate these two together. (Bad news, I know). BUT, it can be done. {insert asterisk here}

How to connect a Magento order to a customer in the database.
If a customer checks out while logged in, this happens by default. However, if a customer did not log in when checking out, and later wants the order associated to their account, follow these steps to tie the two together.

Solution Options

There are two ways to approach this:

  1. Install an extension
  2. Manually edit the database

Associate Customers Order With Account Via a Magento Extension

I know extensions are out there for this, but I have not personally used one and thus will not endorse, recommend, or even link one here for you. But a bit of effort should put you in the right direction.

Update January 5th, 2016

While I stated previously that I didn’t have an endorsement for a Magento Extension for linking a customer to an order through the Magento Admin, I am now endorsing an extension. I feel confident endorsing it because I wrote it. Yes, it’s a shameless plug. But it’s a free extension, so really it’s ok, right?

Magento Extension to Link a Customer to a Guest Order

The PromInc Magento Extension for linking customers and orders is available via Github and will require a manual installation as opposed to using Magento Connect. Feel free to download the code to add to your own Magento install. Installation and usage instructions are also documented on Github.

Associate Customers Order With Account Via Database

What I will share with you however is how to make this correction manually in the database. To do this however, you need database access to your Magento site via either PHP MyAdmin, a 3rd party database tool like MySql Workbench, NovaBench, etc., or command line access.

NOTE : If you were completely lost by that last sentence, I’m assuming you are not a developer and/or a database admin, and this is where you would be best to turn and walk away from this post. :) I’m not trying to be rude but more honest. The setup for those tools requires configuration from your webhost, and the proper knowledge to know how to utilize these tools. Playing in the database isn’t something a novice should be doing – you can create a lot of undesirable results in there if you don’t know what you are doing.

Ok, for those of you that are still reading and understanding, here is the solution you are looking for. I know this solution works for Magento version 1.4.1 and greater.

You will need to know the following information:

  • The Customers’ ID (customer_id)
    • The easiest way to find the Customer ID is to view the customer in the Magento Admin and look at the URL for that customer in the address bar – the Customer ID is the number at the end of the URL.
      https://www.yoursite.com/index.php/guru/customer/edit/id/200490 /
  • The Order ID (entity_id)
    • NOTE : This is the Database entity ID, NOT the Order ID that you use on your invoices.
    • The easiest way to find the Order ID is to open the order in the Magento Admin and look at the URL for that order in the address bar- Order ID it is the number at the end of the URL.
      https://www.yoursite.com/index.php/guru/sales_order/view/order_id/291855 /

There are two tables in the Magento Database that need to be updated:

  • sales_flat_order
  • sales_flat_order_grid
    • NOTE : I believe this table is only used for the Magento Admin

If you are using a GUI based database editing tool like MySQL Workbench, you simply need to edit the Order ID entry in the two tables listed above, setting the customer_id field to the Customer ID found above.

If you prefer to do this via a SQL script, you can use the following two scripts, replacing CUSTOMER ID and Order ID with the appropriate info found above.