Creating and Update Laravel Eloquent

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

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



        
13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 12:57

    Updated: Aug 27 2014 - [updateOrCreate Built into core...]

    Just in case people are still coming across this... I found out a few weeks after writing this, that this is in fact part of Laravel's Eloquent's core...

    Digging into Eloquent’s equivalent method(s). You can see here:

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

    on :570 and :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;
        }
    

    Old Answer Below


    I am wondering if there is any built in L4 functionality for doing this in some way such as:

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

    I did create this method a few weeks back...

    // 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;
    }
    

    I Hope that helps. I would love to see an alternative to this if anyone has one to share. @erikthedev_

提交回复
热议问题