dsxfa26482 2015-12-14 11:28
浏览 35
已采纳

“Laravel 5.1”使用userId添加用户和项目

I have a form where an user can post a project to the database together with making a new user where both are linked together.

Usersid and projects.user_id values in the table.But, I have a small problem. If I get the last id from the users table and use that one +1 for the next id it works. but if an user gets deleted before adding the new project with id it can get really messy when the application launches.

let's say I got the last user as id 5 in the table. but, someone deleted it and I made a new project with a new user the day after.Now the next id will be id 6. but according to my code it reflects 5 in the projects_table but in the users_table it becomes 6.

I was wondering if someone can suggest me a function that I could use for having the right id's?

function for getting the last id

    public static function getLastRow(){
            $data =  DB::table('users')->select('id')
                ->orderBy('id', 'desc')
                ->first();
            return $data->id;
        }

before validator i count the last id for adding it to projects

 $lastidplus = (int)User::getLastRow() + 1;

in my validator i have this :

'user_id' => $lastidplus,

NOTE:: this works but if in the future the last row in the users table gets deleted. there will come an chain reaction of false ids in the corresponding projects table as he will always have 1 difference. and I wantto make that impossible.

  • 写回答

1条回答 默认 最新

  • dongyi0210 2015-12-14 11:48
    关注

    If you are trying to get the ID of a newly created record try:

    $user = User::create(['name'=>'Stefano']);
    $user->id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求