我想在一个组中显示所有与该组具有相同标签的文章。例如:
该小组的标签为:laravel,php,html。然后,我想让所有具有完全相同标签的文章。因此所有带有laravel,php,html标签的文章。
并非所有只有一个标签的文章,只有所有带有相同标签的文章。$ tagIdArray是该组的标签。
我尝试了这段代码:
$tagIdArray = [2,3,4];
$article = Article::with('comments', 'tags')->whereIn('privacy', [1, 2])->where('status', 1)
->where(function ($query) use ($tagIdArray) {
return $query->tags->pluck('id')->all() == $tagIdArray;
})
->latest()->paginate(15);
但我总是收到错误消息:
Undefined property: Illuminate\Database\Eloquent\Builder::$tags
邮政模型
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable')->withTimestamps();
}
标签模型
public function taggable()
{
return $this->morphTo();
}
可标记模型
public function tag()
{
return $this->belongsTo('App\Tag');
}
编辑:
例如,如果我显示所有组,而我想使用关节的随机图像作为组图像。我如何最好地实现这一点?
@foreach ($groups as $group)
{{$group->name}}
<img src="-----load random picture from articles that is in this group------" alt="" />
@endforeach
以下将解决问题:
$tagIdArray = [2,3,4];
$article = Article::with('comments', 'tags')
->whereIn('privacy', [1, 2])
->where('status', 1)
->whereHas('tags', function($query) use ($tagIdArray) {
$query->whereIn('id', $tagIdArray);
}, '>=', count($tagIdArray))
->latest()
->paginate(15);
whereHas()使您仅过滤具有与回调(第二个参数)定义的约束匹配的相关模型(第一个参数)的模型。
除此之外,您可以说应该有多少个与给定约束匹配的相关模型返回模型-这是最后2个参数所做的。上面的代码将返回至少在$ tagIdArray中具有ID的所有标签的文章-它还将包含具有比提供的3个标签更多的标签的文章。如果你想返回都只有在提供广告代码的文章$ tagIdArray,更换> =运算符=。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句