Laravel 5 的updateOrCreate 使用

Laravel Eloquent updateOrCreate()的用法及其重要性。Laravel 提供了updateOrCreate()来帮助我们更新记录(如果存在)和创建(如果不存在)。这种方法帮助我们不用手动检查记录是否存在然后更新,如果不存在则创建。请参阅下面的示例,其中没有 Laravel updateOrCreate()和 Laravel updateOrCreate()

没有 Laravel updateOrCreate() 的示例

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = 'Post 38';
        $description = 'Description for post 38 - updated.';
        $body = 'Body for post 38.';

        $post = Post::where('title', $title)->first();

        if(is_null($post)) {
            $post = new Post([
                'title' => $title,
                'description' => $description,
                'body' => $body
            ]);
            $post->save();
        } else {
            $post->description = $description;
            $post->body = $body;
            $post->update();
        }

        print_r($post);die;
    }
}

Laravel updateOrCreate() 示例

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::updateOrCreate([
            'title' => 'Post 3'
        ], [
            'description' => 'Description for post 3.',
            'body' => 'body for post 3 - updated.'
        ]);

        print_r($post);die;
    }
}

正如您从上面的代码中看到的那样,我们具有相同的更新或创建功能,但是通过 Laravel 的updateOrCreate()方法的实现,我们缩短了代码。