通过Laravel在Mysql中插入数据的最佳方法

通过Laravel在Mysql中插入数据的最佳方法,laravel,Laravel,下面是通过laravel在MySql中插入数据的两种方法 方式1: $post = Post::create([ 'title' => $request->input('title'), 'body' => $request->input('body') ]); $post = new Post; $post->title = $request->input('title'); $post->body = $request->input('bod

下面是通过laravel在MySql中插入数据的两种方法 方式1:

$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
方式2:

$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();

我只想知道哪种方法更好,为什么?谁能告诉我哪种方法更好吗?

Model::create
是一个简单的包装器,如果您看一下它的实现:

public static function create(array $attributes = [])
{
    $model = new static($attributes);

    $model->save();

    return $model;
}
保存()

save()
方法用于保存新模型和更新现有模型。在这里,您可以创建新模型或查找现有模型,逐个设置其属性,最后保存到数据库中

save()
接受完整的雄辩模型实例

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);`

$post->comments()->save($comment);
创建()

当您在
create
方法中传递数组时,可以一次性在模型中设置属性并保存在数据库中

create()
接受普通PHP数组

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

Model::create
是一个简单的包装器,如果您看看它的实现:

public static function create(array $attributes = [])
{
    $model = new static($attributes);

    $model->save();

    return $model;
}
保存()

save()
方法用于保存新模型和更新现有模型。在这里,您可以创建新模型或查找现有模型,逐个设置其属性,最后保存到数据库中

save()
接受完整的雄辩模型实例

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);`

$post->comments()->save($comment);
创建()

当您在
create
方法中传递数组时,可以一次性在模型中设置属性并保存在数据库中

create()
接受普通PHP数组

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

我只是想知道哪种方法更可取。你能具体说明一下吗?Create更可取,因为他说的东西,你可以一次插入数组并保存。如果你看到示例,我在第一个示例中说,我只想知道哪种方法更可取。你能具体说明一下吗?Create更可取,因为他说的东西,你可以一次插入数组并保存。如果你看到示例,我在第一个示例中说的更好