doushi1974 2015-06-05 13:32
浏览 175
已采纳

Symfony2从数据库中查询特定值

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?

  • 写回答

1条回答 默认 最新

  • douwan4993 2015-06-05 14:02
    关注

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?