简体   繁体   中英

Symfony2 querying a specific value form the database

A simple shop. A user has money in his balance account and when he buys something the balance needs to be decreased based on the sum of the cart. I have an action that is redirected if the payment was successful. If it was I want to decrease the balance like this:

  /**
     * @Route("/successfull", name="successfull_purchase")
     * @Template("MediaparkLtUserBundle:User:paymentConfirmed.html.twig")
     */
    public function successfullPurchaseAction(Request $request) {
        $currentUser = $this->getCurrentUser(); // logged users id
        $em = $this->getEntityManager();
        $user = $em->getRepository('MediaparkLtUserBundle:User')->find($currentUser);
        $pay = $em->getRepository('MediaparkLtUserBundle:AccountMovement')->findOneBy(array('user'=>$currentUser));
        $sum = $pay->getAmount();
        $balance = $user->getNonpayableFunds();
        $newBalance = $balance - $sum;

        $user->setNonpayableFunds($newBalance);

        $em->persist($user);
        $em->flush();
        return array('user' => $user, 'pay'=> $pay);
    }

As you can see im querying two tables. In User table im getting the current user. In AccountMovement I am getting the movement based on that user.

So I am trying to get the Amount on the specific time, but I always get the first buy.

For example:

AccountMovement table:

id-1
user_id - 5
amount - 50.00

id-2
user_id - 5
amount - 5.00

With my query I always get the first input, whitch is 50.00. I need to get the last(or current input). How can I do that? Is it possible to do something like this:

$pay = $em->getRepository('MediaparkLtUserBundle:AccountMovement')->findOneBy(array('user'=>$currentUser, 'DESC')); (to get the last input)??

Any ideas?

I think you could the the similar thing:

$pay = $em->getRepository('MediaparkLtUserBundle:AccountMovement')
        ->findBy(array('user'=>$currentUser), array('id' => 'DESC'), 1)[0];

Not ideal, but it should work. Be aware that this could throw OutOfRangeException if no results exist in the database.

Why not store the last amount of money in User itself? Or some other entity which is related to User entity?

Also, be sure to wrap that action in DB transaction via beginTransaction() and commit() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM