Android关于Litepal使用中遇到的表关联/外键的问题


                String part=tempUser.getPart();
                Dishes tempDish=new Dishes();
                tempDish.setName(name);
                tempDish.setPrice(price);
                tempDish.setDishNum(num);
                //---日期----//
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                tempDish.setUpDate(sdf.format(new Date()));
                tempDish.setPart(part);
                tempDish.save();

                tempUser.getMyUp().add(tempDish);
                tempUser.setDishesCount(tempUser.getMyUp().size());
                tempUser.save();

     这段时间在做有关食堂的项目,其中用到了Litepal控制数据库,在这里有两个表Dishes和User,分别为菜品和相应的上传者,tempUser是通过intent从上一个活动中传过来的user对象(代表当前用户),在这时通过两个save保存后,通过sqlite3看不到外键保存(Dishes表中的user_id),头疼了许久。

后来发现,把代码改成以下可以正常储存外键数据,也许是因为intent传过来的对象和litepal的对接有问题而导致的。

                User user=LitePal.find(User.class,tempUser.getId());
                //注意!!此处不能直接用之前的tempUser,而应再次从数据库查找,不然无法正确关联外键
                String part=tempUser.getPart();
                Dishes tempDish=new Dishes();
                tempDish.setName(name);
                tempDish.setPrice(price);
                tempDish.setDishNum(num);
                //---日期----//
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                tempDish.setUpDate(sdf.format(new Date()));
                tempDish.setPart(part);
                tempDish.save();

                user.getMyUp().add(tempDish);
                user.setDishesCount(user.getMyUp().size());
                user.save();

   

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值