Laravel雄辩关系问题 [英] Laravel Eloquent Relationship issue

查看:221
本文介绍了Laravel雄辩关系问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型 - 博客,帖子,评论。
博客有很多帖子
发表了很多评论



当我写

 返回Blog :: with('posts','posts.comments') - > get(); 

它将给所有博客添加帖子和评论。
但是我将如何获得管理员用户创建的那些博客,即在注释表中的user_id。在哪里写 - >其中条件。

 返回博客::用( '信息', 'posts.comments') - 化合物其中( 'comments.user_id', '=', '23') - >得到(); 

给出错误。

  SQLSTATE [42P01]:未定义的表:7错误:表注释缺少FROM子句条目
LINE 1:select * fromblogswherecomments。is _...
^(SQL:select * fromblogswherecomments。user_id= 23)
解决方案

如果我理解正确,您将得到所有已被特定用户评论的帖子。



从您目前为止所做的一切, whereHas()可能是你正在寻找的,这是你可以这样做的。

  return Blog :: with('posts.comments')
- > whereHas('posts.comments',function($ q)use($ user){
$ q-> where('comments.user_id',$ user-> id);
}) - > get();

来源: http://laravel.com/docs/ 5.0 /雄辩#查询关系


I have three models - Blog,Post,Comment. Blog has many Post Post has many Comment

when I write

return Blog::with('posts','posts.comments')->get();

It will give all the blogs with posts and comments. But how I will get those blogs which are created by admin user i.e. user_id which is in comments table. Where to write ->where condition.

return Blog::with('posts','posts.comments')->where('comments.user_id','=','23')->get();

gives error.

SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "comments"
LINE 1: select * from "blogs" where "comments"."is_...
^ (SQL: select * from "blogs" where "comments"."user_id" = 23)

How to solve this issue.

解决方案

If I understand correctly, You wan to get all the posts that have been commented by a specific user.

From what you have done so far,whereHas() might be what you are looking for. This is how you could do it.

return Blog::with('posts.comments')
                ->whereHas('posts.comments', function($q) use ($user){
                  $q->where('comments.user_id', $user->id);
              })->get();

source: http://laravel.com/docs/5.0/eloquent#querying-relations

这篇关于Laravel雄辩关系问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆