Creating and Update Laravel Eloquent

后端 未结 13 1324
广开言路
广开言路 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

    Actually firstOrCreate would not update in case that the register already exists in the DB. I improved a bit Erik's solution as I actually needed to update a table that has unique values not only for the column "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);
        }
    }
    

    Then you'd use it like this:

    Model::createOrUpdate(
            array(
        'id_a' => 1,
        'foo' => 'bar'
            ), array(
        'id_a' => 1
            )
    );
    
    0 讨论(0)
提交回复
热议问题