我有一个关于如何使用Eloquent按类别获取特定帖子的相关帖子的问题。我知道如何在纯MySQL中完成它,但我确信Eloquent会有更好的替代方案。
我的表格是:帖子类别post_category(pivot)
我已经建立了必要的Eloquent连接,所以我想做类似的事情:$post->categories()->posts()->exclude($post)->get()
。
当然这不会奏效。我在posts()上收到错误,因为" Builder没有方法posts()",但希望你能得到这个想法。你会如何用Eloquent做到这一点?
答案 0 :(得分:1)
很难说你想要达到什么目标,机器人可能你想得到:
Posts::whereIn('id', $post->categories()->lists('id'))->whereNot('id',$post->id)->get();
答案 1 :(得分:0)
关于Eloquent关系的一个令人困惑的部分是,定义关系的模型上的方法会在调用它时调用关系对象:
$posts->categories();
要返回附加到帖子的类别模型集合,您应该使用以下内容:
Post::find(primary key of post)->categories;
或者获取所有帖子并分别遍历模型:
$posts = Post::all();
foreach($posts as $post) {
$post->categories;
}
这是我发现在学习使用Eloquent关系方法时非常有帮助的资源:http://codeplanet.io/laravel-model-relationships-pt-1/
答案 2 :(得分:0)
我正尝试按类别获取我的相关帖子,并在Google上进行搜索并到达此处。 我做到了,效果很好。
public function getSingle($slug){
$post = Post::where('slug', '=', $slug)->first();
$tags=Tag::all();
$categories=Category::all();
$related= Post::where('category_id', '=', $post->category->id)
->where('id', '!=', $post->id)
->get();
return view('blog.show')
->withPost($post)
->withTags($tags)
->withCategories($categories)
->withRelated($related);
}
在我的视图(“ blog.show”)
$post->title
$post->content
//related posts
@foreach($related as $posts)
$posts->title
$posts->category->name
@endforeach
我不知道这是否是正确的方法,但这对我有用。我希望这对某人有帮助
答案 3 :(得分:0)
为什么不在搜索具有相同类别ID的帖子时定义“相关帖子”关系?
然后,您只需做$post->relatedposts
...
您正在使它变得过于复杂imo ...