【发布时间】:2018-04-03 13:01:01
【问题描述】:
我有三个模型 Post.php 是主要模型,与其他两个模型 Category.php 和 Tags.php 相关,它们的方式如下:
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function tags()
{
return $this->belongsToMany('App\Tags');
}
}
我正在尝试获取具有相同标签名称的博客文章的所有类别名称。
这是我尝试过的:
public function getByTag($tag)
{
$tags = Tag::where('name','=',$tag)->first();
$posts = $tags->posts()->get();
foreach ($posts as $post) {
echo($post->category->name.'<br>');
}
}
上面的代码在某种程度上完成了这项工作(重复以前使用的类别,因为它正在打印每个帖子的类别)。而且我只想打印一次所有相关的类别名称。
如果有人能建议我正在寻找的输出的最佳查询方法,我将非常感激?
更新 添加表结构
posts
id - integer
title - string
content - text
category_id -integer
category
id - integer
name - string
tags
id - integer
name - string
posts_tags
id - integer
post_id - integer
tag_id -integer
【问题讨论】:
-
你能告诉我你的三个表结构吗?
-
什么是
$testsvar?还有,beetwen的帖子和博客是什么关系? -
您想使用 hasManyThrough 在博客和类别之间创建关系laravel.com/docs/5.6/eloquent-relationships#has-many-through
标签: php laravel laravel-5.5