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

   

你可能感兴趣的:(Android关于Litepal使用中遇到的表关联/外键的问题)