在 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/