【问题标题】:How to search all articles belongs to a tag in laravel如何在laravel中搜索属于一个标签的所有文章
【发布时间】:2016-12-29 02:32:52
【问题描述】:

文章模型

class Article {
    public function Tag(){
      return $this->belongsToMany('App\Tag');
    }
}

标签模型

class Tag {
    public function Article(){
      return $this->belongsToMany('App\Article');
    }
}

数据透视表

article_id === tag_id

我想搜索所有使用标签名称的书籍。我该怎么做?

我的解决方案

public function tagArticle($name)
{
    $tags = $this->tag->where('name',$name)->get();
    $articles = [];
    foreach ($tags as $tag) {
        $articles[] = $tag->articles;
    }
    return view('front.home')->with('articles',$articles);
}

这是我的解决方案,但我认为它不是很好。有没有人有其他解决方案?谢谢。

【问题讨论】:

  • 您提到了Article & Tag,但是您想使用标签搜索books,并且您的代码显示您正在获取poststag,那么它们之间的关系是什么?这 4 个实体?
  • 我已经编辑了问题。共有三个表,article,tag,article_tag。

标签: mysql laravel laravel-5 laravel-5.3


【解决方案1】:

使用whereHas()

 $articles=Article::whereHas('tags',function($query)
        {
            $query->where('name',$name);
        })->get();

【讨论】:

    【解决方案2】:

    使用mapflatten 会更好。

    $tags = $this->tag->where('name',$name)->get();
    
    $articles = $tags->map(function($v) { 
        return $v->articles; 
    })
    ->flatten()
    ->all();
    

    flatten 将返回同一级别的所有文章

    [
       articleObject,
       articleObject,
       articleObject,
    ]
    

    更多详情https://laravel.com/docs/5.3/collections#method-map

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多