如何检查模型是否被特定标签标记

how to check if a model is tagged by a specific tag

我有模型实体和相关模型标签。后者用作标签,因此关系由枢轴 table

提供服务

我想这很容易,但我迷路了。

public function tags()
{
    return $this->belongsToMany('App\Models\Tag', 'entity_tags', 'entity_id', 'tag_id');
}

现在,在我看来我可以列出所有标签: 它们被定义为

{!! 
               join(', ',
                    array_map(function($o) {
                        return link_to_route('entities.profile',
                        $o->name,
                        [$o->id],
                        ['class' => 'ui blue tag button']
                        );}, 
                        $object->tags->all())
            ) !!}

我的问题:

在BLADE中如何检查Entity对象是否有特定的容量?

在我的控制器 SHOW 方法中,我得到一个实体:

$object = Entity::find(34);

如果实体被某个标签标记,我想做某事

@if($object->capacities .... has tag=  3
 // do things here
@endif

感谢

您可以向您的实体 class 添加一个 public 方法,这样您就可以检查此实体上的现有标签:

<?php
public function hasTag($tagToMatch)
{
   foreach ($this->tags as $tag)
   {
      if ($tag->id == $tagToMatch)
         return (true);
   }
   return (false);
}

这将允许您在视图中使用以下代码:

@if ($entity->hasTag(3))
   Do something
@endif

你可以检查一个实体是否有这样的特定标签:

@if($entity->tags()->where('id', 3)->exists()) //.... has tag=  3
   // do things here
@endif