简体   繁体   English

Laravel eloquent 关系在按 id 搜索时将无法正常工作

[英]Laravel eloquent relations won't work as supposed to when searching by id

I currently have 3 tables:我目前有3张桌子:

Posts:
-id
-text
-user_id
Comments:
-id
-text
-post_id
-user_id
Likes:
-id
-user_id
-comment_id

I want to get both Comments and Likes on those comments on my show() controller of Posts.我想在我的show() controller 的帖子中获得评论和喜欢。 This code in my Models seemed to work when using all() , however it completely breaks when im trying to search by id .使用all()时,我的Models中的这段代码似乎可以工作,但是当我尝试按id搜索时它完全中断。 It always returns all Posts , even though it should only get one.它总是返回所有Posts ,即使它应该只得到一个。

class Posts extends Model
{
    public function comments(){
        return $this->hasMany('App\Models\Comments', 'post_id', 'id');
    }
    public function comment_likes(){
        return $this->hasManyThrough(
            '\App\CommentLikes',
            '\App\Models\Comments',
            'post_id', 'comment_id', 'id'
        );
    }
}

And controller code:和 controller 代码:

  public function show($id){
        $query =\App\Models\Posts::find($id)->with('comments')->with('comment_likes')->get();
        if(is_null($query)){
            return response()->json(['Not found'], 404);

        }
        return response()->json($query, 200);
    }

Is that even proper way of doing it?这甚至是正确的做法吗?

You are messing up query builders and models, the call sequence you have now will execute a new ->get() query from the model, therefor returning multiple posts.您正在搞乱查询构建器和模型,您现在拥有的调用序列将从 model 执行新的->get()查询,因此返回多个帖子。

This happens as ->find() executes a query, returns 1 element where the id is the parameter.这发生在->find()执行查询时,返回 1 个元素,其中 id 是参数。 This is now an Eloquent model, therefor you should not call with() and get() on this.现在这是一个 Eloquent model,因此您不应该调用with()get() You do that and this will execute a new query, therefor selecting all posts.您这样做,这将执行一个新查询,从而选择所有帖子。

If you rearrange the order, it should work as expected.如果您重新排列顺序,它应该会按预期工作。

\App\Models\Posts::with('comments')->with('comment_likes')->find($id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM