Php 是$post->;评论()->;create()比Laravel中的Comment::create()更昂贵?

Php 是$post->;评论()->;create()比Laravel中的Comment::create()更昂贵?,php,sql,laravel,Php,Sql,Laravel,在Laravel PHP框架中,如果两个表之间存在关系,例如一篇文章可以有一条或多条注释,则可以通过以下方式创建文章的注释: // Option 1 $post->comments()->create(['text' => 'Greate article...']); 或 当然,这取决于具体情况。下面是我的案例 对于这两个选项,无论ID为1的帖子是否存在,都已在表单请求中验证帖子ID 1 由于某些原因,我已经需要首先从数据库中检索post,因此我已经有了post模型 在上

在Laravel PHP框架中,如果两个表之间存在关系,例如一篇文章可以有一条或多条注释,则可以通过以下方式创建文章的注释:

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

当然,这取决于具体情况。下面是我的案例

  • 对于这两个选项,无论ID为1的帖子是否存在,都已在表单请求中验证帖子ID 1
  • 由于某些原因,我已经需要首先从数据库中检索post,因此我已经有了post模型
在上述情况下,
选项1
是否比
选项2
更贵?

如果它“更便宜”,就不会太贵。您正在创建查询生成器的实例,但实际上并没有查询任何内容。因此,在本例中,它只是在您正在创建的新模型上添加post_id


我不认为这是您太担心的事情。

您可以使用
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);
    }
}
测试:

因此您可以看到,在我的测试场景中,
create
的关联方式实际上慢了大约3%

如果你想进一步试验,我已经准备好了

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
]