Php Laravel-显示带有特定标签的文章数量

Php Laravel-显示带有特定标签的文章数量,php,laravel,laravel-5,Php,Laravel,Laravel 5,我有以下输出所有标记名的foreach循环: <section class="popular-tags-section"> <ul class="popular-tags-listings"> @foreach($tags as $tag) <li><a href="">{{ $tag->tag }}(3)</a></li> @endForEach

我有以下输出所有标记名的foreach循环:

<section class="popular-tags-section">
    <ul class="popular-tags-listings">
        @foreach($tags as $tag)  
          <li><a href="">{{ $tag->tag }}(3)</a></li>
        @endForEach   
    </ul>
</section>
现在,我如何动态显示标记为
javascript
的文章数量

其他信息

博客文章表:

标签表:

网页编码:

class PagesController extends Controller {

    public function index() {
        // Grap the latest post .. the last 10 :)
        $recentPost = Admin::orderBy('created_at' , 'desc')->take(10)->get();
        $tags = Tags::all();;
        return view('pages.index')->with('recentPost' , $recentPost)->with('tags' , $tags );
    }

}
博客文章:

class Admin extends Model {

    public $table = "admin";
    // public $timestamps = false;
    protected $fillable = [
        'title',
        'description',
        'keywords',
        'blog_content',
        'tag',
        'slug',
        'filePath'
    ];

}
标记模式:

class Tags extends Model {
    public $table = "tags";
    public $timestamps = false;
    protected $fillable = ['tag'];
}

使用以下方法为每个标签获取包含计数物品的标签:

如果您想在不实际加载的情况下计算关系中的结果数,可以使用withCount方法,该方法将在结果模型上放置一个
{relation}\u count

显示指定标签的物品数量:

{{ $tag->tag }} ({{ $tag->articles_count }})
这将适用于标签模型中正确定义的
文章
关系。这里的最佳选择是多对多,因此您必须有一个透视表和
articles
关系,定义如下:

public function articles()
{
    return $this->belongsToMany(Article::class);
}
在你的控制器中,你会这样做

Tag::withCount('posts')->get();

我不太确定它是否能起作用,因为我不太确定它的结构。如果有任何错误,请告诉我。

“博客文章表中有一列名为
标记
”-你的意思是
tag\u id
对吗?如果你能更精确地展示你的模型和表格结构,那就太好了。@imrealashu编辑,谢谢:)
tag
model。@imrealashu完成了我认为首先我需要创建一个外键吗?也许
Admin
表中的
tag
字段应该引用
Tags
表中的
ID
字段?我不知道您想要使用什么结构,这是您的决定。但是如果你想让我的答案中的代码起作用,你需要定义标签和文章模型之间的
hasMany()
(一对多)或
belongtomany()
(多对多和透视表)关系。很抱歉再次问了一个愚蠢的问题,我能有
hasMany()
belongtomany()吗
在没有通过外键连接两个表的情况下,我的模型中的关系?您可以跳过创建约束,但仍然需要为
hasMany()
创建一个键,为
belongToMany()
创建一个透视表(将有两个键)。
public function articles()
{
    return $this->belongsToMany(Article::class);
}
class Tags extends Model {
public $table = "tags";
public $timestamps = false;
protected $fillable = ['tag'];

public function posts()
{
    return $this->belongsToMany(Post::class);
}}
Tag::withCount('posts')->get();