gpt4 book ai didi

mysql - 如何在laravel中搜索属于某个标签的所有文章

转载 作者:可可西里 更新时间:2023-11-01 07:34:15 25 4
gpt4 key购买 nike

文章模型

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);
}

This is my solution, but I don't think it's good. Does anyone has other solutions? Thank you.

最佳答案

使用whereHas()

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

关于mysql - 如何在laravel中搜索属于某个标签的所有文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41372384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com