Creating and Update Laravel Eloquent

后端 未结 13 1323
广开言路
广开言路 2020-11-27 11:59

What\'s the shorthand for inserting a new record or updating if it exists?



        
相关标签:
13条回答
  • 2020-11-27 12:38

    Here's a full example of what "lu cip" was talking about:

    $user = User::firstOrNew(array('name' => Input::get('name')));
    $user->foo = Input::get('foo');
    $user->save();
    

    Below is the updated link of the docs which is on the latest version of Laravel

    Docs here: Updated link

    0 讨论(0)
  • 2020-11-27 12:42

    Save function:

    $shopOwner->save()
    

    already do what you want...

    Laravel code:

        // If the model already exists in the database we can just update our record
        // that is already in this database using the current IDs in this "where"
        // clause to only update this model. Otherwise, we'll just insert them.
        if ($this->exists)
        {
            $saved = $this->performUpdate($query);
        }
    
        // If the model is brand new, we'll insert it into our database and set the
        // ID attribute on the model to the value of the newly inserted row's ID
        // which is typically an auto-increment value managed by the database.
        else
        {
            $saved = $this->performInsert($query);
        }
    
    0 讨论(0)
  • 2020-11-27 12:42

    One more option if your id isn't autoincrement and you know which one to insert/update:

    $object = MyModel::findOrNew($id);
    //assign attributes to update...
    $object->save();
    
    0 讨论(0)
  • 2020-11-27 12:44

    If you need the same functionality using the DB, in Laravel >= 5.5 you can use:

    DB::table('table_name')->updateOrInsert($attributes, $values);
    

    or the shorthand version when $attributes and $values are the same:

    DB::table('table_name')->updateOrInsert($values);
    
    0 讨论(0)
  • 2020-11-27 12:44

    check if a user exists or not. If not insert

    $exist = DB::table('User')->where(['username'=>$username,'password'=>$password])->get();
    if(count($exist)  >0) {
        echo "User already exist";;
    }
    else  {
        $data=array('username'=>$username,'password'=>$password);
        DB::table('User')->insert($data);
    }
    Laravel 5.4           
    
    0 讨论(0)
  • firstOrNew will create record if not exist and updating a row if already exist. You can also use updateOrCreate here is the full example

    $flight = App\Flight::updateOrCreate(
        ['departure' => 'Oakland', 'destination' => 'San Diego'],
        ['price' => 99]
    ); 
    

    If there's a flight from Oakland to San Diego, set the price to $99. if not exist create new row

    Reference Doc here: (https://laravel.com/docs/5.5/eloquent)

    0 讨论(0)
提交回复
热议问题