【问题标题】:Is $post->comments()->create() more expensive than Comment::create() in Laravel?$post->comments()->create() 是否比 Laravel 中的 Comment::create() 贵?
【发布时间】:2020-12-03 00:31:08
【问题描述】:

在 Laravel PHP 框架中,假设你有两个表之间的关系,例如一篇帖子可以有一个或多个 cmets,您可以通过以下方式创建帖子的 cmets:

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

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

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

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

在上述这些情况下,Option 1 是否比 Option 2 贵?

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多