【问题标题】:how to check if a model is tagged by a specific tag如何检查模型是否被特定标签标记
【发布时间】:2015-08-01 04:55:15
【问题描述】:

我有模型实体和相关模型标签。后者用作标签,因此关系由数据透视表提供服务

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

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

谢谢

【问题讨论】:

  • $object->tags->all() 什么是 $object 这里是 $o 吗?

标签: laravel laravel-5 relationship blade


【解决方案1】:

您可以向您的 Entity 类添加一个公共方法,这样您就可以检查该实体上的现有标签:

<?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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多