Reputation: 1499
class Article {
public function Tag(){
return $this->belongsToMany('App\Tag');
}
}
class Tag {
public function Article(){
return $this->belongsToMany('App\Article');
}
}
article_id === tag_id
I want to search all books use a tag's name. How can I do this?
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.
Upvotes: 4
Views: 949
Reputation: 3538
Use map
with flatten
would be better.
$tags = $this->tag->where('name',$name)->get();
$articles = $tags->map(function($v) {
return $v->articles;
})
->flatten()
->all();
The flatten will return all articles in the same level
[
articleObject,
articleObject,
articleObject,
]
More detail https://laravel.com/docs/5.3/collections#method-map
Upvotes: 1
Reputation: 3266
Using whereHas()
$articles=Article::whereHas('tags',function($query)
{
$query->where('name',$name);
})->get();
Upvotes: 2