php - $post->comments()->create() 是否比 Laravel 中的 Comment::create() 更昂贵?

标签 php sql laravel

在 Laravel PHP Framework 中,假设两个表之间存在关系,例如一个帖子可以有一个或多个评论,您可以通过以下方式创建帖子的评论:

// Option 1
$post->comments()->create(['text' => 'Greate article...']);

// Option 2
Comment::create([
    'post_id' => 1,
    'text' => 'Greate article...',
]);

当然,这要视情况而定。以下是我的案例。

  • 对于这两个选项,无论 ID 为 1 的帖子是否存在,都已在表单请求中验证了帖子 ID 1。
  • 由于某些原因,我已经需要先从数据库中检索帖子,因此我已经有了帖子模型。

在上述这些情况下,选项 1 是否比选项 2 更昂贵?

最佳答案

您可以通过 listening to the queries 测试您的应用程序进行的查询使用 DB::listen()

我已将以下内容设置为测试:

迁移:

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('title');
    $table->string('content');
    $table->timestamps();
});

Schema::create('comments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('post_id');
    $table->string('text');
    $table->timestamps();
});

模型:

class Post extends Model
{
    protected $guarded = [];
    
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

class Comment extends Model
{
    protected $guarded = [];
    
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

测试:

$post = Post::create([
    'title' => 'Hello World',
    'content' => 'Here I am!',
]);

$queries = collect();

DB::listen(function ($query) use ($queries) {
    $queries->push($query->time);
});

for ($i = 1; $i <= 3000; $i += 1) {
    Comment::create([
        'post_id' => $post->id,
        'text' => 'Facade '.$i,
    ]);
    
    $post->comments()->create([
        'text' => 'Relation '.$i,
    ]);
}

$totalTime = [0, 0];

foreach ($queries as $idx => $time) {
    $totalTime[$idx%2] += $time;
}

return [
    'facade' => $totalTime[0],
    'relation' => $totalTime[1],
];

这个输出:

array:2 [▼
  "facade" => 1861.3
  "relation" => 1919.9
]

所以你可以看到 create 的关系方式在我的测试场景中实际上慢了大约 3%。

我准备了这个implode如果您想进一步试验。

关于php - $post->comments()->create() 是否比 Laravel 中的 Comment::create() 更昂贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63390404/

相关文章:

php - 如何安全地实现 'Token Based Authentication' 以访问使用 PHPFox 开发的网站资源(即功能和数据)?

MySQL:根据不同的列减去不同的行

mysql - 使用不同的 where 语句在 MySQL 查询中选择多个计数

php - 如何在 Laravel 5 表单中使用 Markdown 作为文本区域输入字段?

php - 检查我发送的电子邮件是否已阅读

php - 使用 mysql 和 php 合并和存储多个 csv 文件的最佳方法

C# foreach 循环迭代与查询执行时的列表

php - 如何使用命令行界面 (CLI) 重命名 Laravel Controller ?

php - 来自外部源的 Laravel Eloquent 无表数据

php - 如何使用在 mySQL 数据库上运行的 PHP 脚本中的循环来访问枢轴行(可以是任何行)之前和之后的行?