这很好但我想知道的是,如果有更好的方法在Laravel中搜索标签。感谢。
标记模型:
class Tag extends Model
{
public function noticias()
{
return $this->morphedByMany('App\Models\Noticia', 'taggable');
}
// ...
}
Noticia 型号:
class Noticia extends Model
{
public function tags()
{
return $this->morphToMany('App\Models\Tag', 'taggable');
}
// ...
}
SearchController
public function tag($id){
$noticias= Noticia::all();
$data['noticias'] = [];
foreach($noticias as $value){
foreach($value->tags as $tag){
if($tag->id == $id){
$data['noticias'][] = $value;
}
}
}
return view('web.buscar.index');
}
答案 0 :(得分:2)
试试这个,
public function tag($id){
$noticicas = Noticia::has(['tags'=> function($query) use($id){
return $query->where('id',$id);
}])->get();
dd($noticicas);
//you can also, get the tag with the id you send, and then get all the `Noticias` for it
$tag = Tag::find($id);
$noticias = $tag->noticias->with(["tags"]); // the with is in case you want to show all the tags from the news
}
答案 1 :(得分:2)
使用whereHas()
$noticias= Noticia::with('tags')->whereHas('tags', function($q) use ($id){
$q->where('id',$id);
})->get();
仅限ids
使用pluck()
$noticias= Noticia::whereHas('tags', function($q) use ($id){
$q->where('id',$id);
})->pluck('id');