简体   繁体   中英

Create record with id

I need to import the data from a different database and transfer it to the new database. but the ID information of the members is required for the relationship. I have to carry them too. Therefore, I have to fill in the ID column which is increased as AUTOINCREMENT.

My Migrate Controller

 public function migrate(BackupUser $buser, User $user)
            {
                $backup_user = $buser->get();

                foreach ($backup_user as $bulk) {
                    $user->create([
                        'id'         => $bulk->uye_id,
                        'name'       => $bulk->uye_nick,
                        'email'      => $bulk->uye_mail,
                        'password'   => $bulk->uye_sifre,
                        'created_at' => $bulk->uye_tarih
                    ]);
                }
            }

when I do this, the AUTOINCREMENT increases normally and I can not get the ID information of the previous members.

What is the best way to do this?

I think you are trying to take database from joomla or wordpress to laravel.

If I need to do this . my approach would be to store first all base tables without id and then with stored id generated after insertion would be in related tables. So the steps would be

  S1:  store new `user` and get `id`
  S2:  relate with other table like `role` with `user_id`
  Loop again till last row

By default, the id field for User is not fillable by mass assignment like you're doing. If you want to assign it, you must add 'id' to the array of fillable fields in the user class.

app/User.php

...
class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id', 'name', 'email', 'password',
    ];
...

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