如何直接在通过路由获取的对象上调用“ with”,其结果与通过“ where”获取的结果相同?

 收藏

How do I call with directly on an object thats been automagically fetched through a route with the same results as if it were fetched through where?

让我通过代码来解释!

我的路线(两者相同):

Route::get('post/{post}', 'PostsController@show');

选择1:

我的控制器:

public function show(Post $post){
    $postWithComments = Post::where('id', $post->id)->with('comments')->first();
}

输出:预期帖子的评论。

选择2:

我的控制器:

public function show(Post $post){
    $postWithComments = $post->with('comments')->first();
}

输出:所有帖子开头的评论。

所需的输出:与备用输出相同。

How can I modify the query in alternative 2 to output the same as alternative 1? I am thinking that it is unnecessary to make first the where-request as I already have the object loaded. So I am thinking that I would want to do this to reduce DB calls. Or am I thinking wrong?

回复
  • 占领网吧 回复

    有两种解决方法:

    • Query related data with lazy loading:

      $post->comments; // this did the trick - comments for post will queried here
      return $post;  // here posts already has comments collection
      
    • Setup model binding and use eager loading:

      At your Post model add resolveRouteBinding method:

      class Post extends Model 
      {
          public function resolveRouteBinding($id)
          {
              return $this->where('id', $id)->with(['comments'])->first();
          }
      }
      

      Then your controller will recieve Post instance with already loaded comments