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

问题描述

在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的帖子。
  • 由于某些原因,我已经需要首先从数据库中检索帖子,因此我已经有了帖子模型。

在上述情况下,Option 1Option 2贵吗?

解决方法

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

我已经设置了以下内容作为测试:

迁移:

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

,

如果它是“便宜”的,则不会明显。您正在创建查询构建器的实例,但实际上并没有查询任何内容。因此,在这种情况下,它仅在您正在创建的新模型上添加post_id。

我认为您不必担心太多。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...