首页 文章

创建和更新Laravel Eloquent

提问于
浏览
118

如果新记录不存在,插入新记录或更新的简写是什么?

<?php

$shopOwner = ShopMeta::where('shopId', '=', $theID)
    ->where('metadataKey', '=', 2001)->first();

if ($shopOwner == null) {
    // Insert new record into database
} else {
    // Update the existing record
}

13 回答

  • 1

    与firstOrCreate方法一样, updateOrCreate 持久化模型, so there's no need to call save()

    // If there's a flight from Oakland to San Diego, set the price to $99.
    // If no matching model exists, create one.
    
    $flight = App\Flight::updateOrCreate(
       ['departure' => 'Oakland', 'destination' => 'San Diego'],
       ['price' => 99]
    );
    

    并为您的问题

    $shopOwner = ShopMeta::updateOrCreate(
       ['shopId' => $theID, 'metadataKey' => '2001'],
       ['other field' => 'val' ,'other field' => 'val', ....]
    );
    
  • 43

    检查用户是否存在 . 如果没有插入

    $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
    
  • 3

    以下是“lu cip”所讨论的完整示例:

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

    以下是Laravel最新版本中文档的更新链接

    文档:Updated link

  • 189

    这与updateOrCreate()不一样吗?它类似但不一样 . updateOrCreate()一次只能用于一行,不允许批量插入 . InsertOnDuplicateKey将适用于许多行 .

    https://github.com/yadakhov/insert-on-duplicate-key

  • 2

    更新日期:2014年8月27日 - [updateOrCreate内置于核心...]

    万一人们仍然会遇到这个问题...我在写完这篇文章几个星期后发现,这实际上是Laravel的Eloquent核心的一部分......

    深入研究Eloquent的等效方法 . 你可以在这里看到:

    https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553

    on:570和:553

    /**
         * Create or update a record matching the attributes, and fill it with values.
         *
         * @param  array  $attributes
         * @param  array  $values
         * @return static
         */
        public static function updateOrCreate(array $attributes, array $values = array())
        {
            $instance = static::firstOrNew($attributes);
    
            $instance->fill($values)->save();
    
            return $instance;
        }
    

    下面的旧答案


    我想知道是否有任何内置的L4功能以某种方式执行此操作,例如:

    $row = DB::table('table')->where('id', '=', $id)->first();
    // Fancy field => data assignments here
    $row->save();
    

    几个星期前我确实创造了这种方法......

    // Within a Model extends Eloquent
    public static function createOrUpdate($formatted_array) {
        $row = Model::find($formatted_array['id']);
        if ($row === null) {
            Model::create($formatted_array);
            Session::flash('footer_message', "CREATED");
        } else {
            $row->update($formatted_array);
            Session::flash('footer_message', "EXISITING");
        }
        $affected_row = Model::find($formatted_array['id']);
        return $affected_row;
    }
    

    我希望有所帮助 . 如果有人可以分享,我很乐意看到替代品 . @erikthedev_

  • 0

    如同 Laravel >= 5.3 ,如果有人仍然好奇如何以简单的方式这样做 . 它可以通过使用: updateOrCreate() .

    例如,对于问题,您可以使用以下内容:

    $matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
    ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);
    

    上面的代码将检查ShopMeta表示的表格,除非模型本身没有另外定义,否则很可能是 shop_metas

    它会尝试找到条目

    专栏 shopId = $theID

    专栏 metadateKey = 2001

    如果它找到,那么它会将找到的行 shopOwner 更新为 New One .

    如果它找到多个匹配的行,那么它将更新第一行,这意味着哪个行具有最低的主 id .

    如果根本找不到,那么它将插入一个新行:

    shopId = $theIDmetadateKey = 2001shopOwner = New One

    Notice 检查您的模型是否为 $fillable ,并确定您要在其中定义要插入或更新的每个列名称,其余列具有默认值或其 id 列自动递增1 .

    否则在执行上面的示例时会抛出错误:

    Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'
    

    由于在插入新行时会有一些需要值的字段,因此无法在_679061中定义它或者它没有默认值 .

    有关更多参考,请参阅Laravel文档:https://laravel.com/docs/5.3/eloquent

    一个例子是:

    // If there's a flight from Oakland to San Diego, set the price to $99.
    // If no matching model exists, create one.
    $flight = App\Flight::updateOrCreate(
        ['departure' => 'Oakland', 'destination' => 'San Diego'],
        ['price' => 99]
    );
    

    这几乎清除了一切 .

    我希望它有所帮助

  • 16

    保存功能:

    $shopOwner->save()
    

    已经做你想要的......

    Laravel代码:

    // 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);
        }
    
  • 5
    $shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));
    

    然后进行更改并保存 . 请注意,如果未找到插入,则firstOrNew不会执行插入,如果您确实需要,那么它的firstOrCreate .

  • 67

    如果您需要使用 DB 的相同功能,在Laravel >= 5.5 中您可以使用:

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

    $attributes$values 相同时的简写版本:

    DB::table('table_name')->updateOrInsert($values);
    
  • 1

    firstOrNew 将创建记录(如果不存在)并更新行(如果已存在) . 你也可以使用 updateOrCreate 这里是完整的例子

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

    如果有从奥克兰飞往圣地亚哥的航班,请将价格定为99美元 . 如果不存在则创建新行

    参考文档:(https://laravel.com/docs/5.5/eloquent

  • 1

    如果您的id不是自动增量并且您知道要插入/更新哪个,则还有一个选项:

    $object = MyModel::findOrNew($id);
    //assign attributes to update...
    $object->save();
    
  • 3

    实际上,如果数据库中已存在该寄存器, firstOrCreate 将不会 update . 我改进了一点Erik的解决方案,因为我实际上需要更新一个具有唯一值的表,而不仅仅是列"id"

    /**
     * If the register exists in the table, it updates it. 
     * Otherwise it creates it
     * @param array $data Data to Insert/Update
     * @param array $keys Keys to check for in the table
     * @return Object
     */
    static function createOrUpdate($data, $keys) {
        $record = self::where($keys)->first();
        if (is_null($record)) {
            return self::create($data);
        } else {
            return self::where($keys)->update($data);
        }
    }
    

    然后你会像这样使用它:

    Model::createOrUpdate(
            array(
        'id_a' => 1,
        'foo' => 'bar'
            ), array(
        'id_a' => 1
            )
    );
    
  • 0

    就像上面发表的@JuanchoRamone一样(感谢@Juancho)它对我来说非常有用,但是如果你的数据是数组,你应该修改一下这样的:

    public static function createOrUpdate($data, $keys) {
        $record = self::where($keys)->first();
        if (is_null($record)) {
            return self::create($data);
        } else {
            return $record->update($data);
        }
    }
    

相关问题