我正在尝试用数据透视表在3个表之间建立关系。由于count()
方法,我只想雄辩地说。
这是我的桌子。
brands: id, name
posts: id, title
tags: id, name, brand_id (fk)
post_tag: post_id (fk), tag_id (fk)
说明:
在PostsController
中,我将获取趋势标签(如果标签名称等于品牌名称,则为Brand),以进行这样的订单
protected function getTrends($model)
{
return $model::has('posts', '>=', '1')->withCount(['posts' => function($q) {
$q->whereDate('created_at', '>', \Carbon\Carbon::now()->subWeek());
}])->orderBy('posts_count', 'DESC')->take(10)->get();
}
这正是我真正想做的:
$brand->posts()->count()
来获取帖子数,以使getTrends函数起作用。我在品牌模型上尝试了hasManyThrough,但未从post_tag数据透视表中选择ID。因此,这向我显示了错误的结果。
我不确定该怎么办。也许我犯了一个简单的错误,但是由于尝试了很多小时而看不到它。
编辑
getTrends函数的用法。
\\PostsController;
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(10, ['*'], 'sayfa');
//Get Popular brands of the week by created posts count
$popularBrands = $this->getTrends('App\Brand');
//Get Popular products of the week by created posts count
$popularProducts = $this->getTrends('App\Product');
$popularPosts = Post::popularWeek()->take(10)->get();
$data = ['posts', 'popularBrands', 'popularProducts', 'popularPosts'];
return view('posts.index', compact($data));
}
这意味着产品或品牌可以成为趋势标签。
posts.index的刀片视图
@foreach($popularBrands as $popularBrand)
@if($popularBrand->posts_count > 0)
<div class="col-12 {{ $loop->last ? 'mb-0' : 'mb-2' }}">
<a href="{{ route('brand.posts', $popularBrand->slug) }}" class="row nodecoration align-items-center" data-toggle="tooltip" data-placement="left" data-title="{{ $popularBrand->name }}">
<span class="col-auto col-lg p-0 text-truncate" ># {{ $popularBrand->name }}</span>
<span class="col col-lg-auto text-right p-0 font-14 text-muted">{{ $popularBrand->posts_count }} konu</span>
</a>
</div>
@endif
@endforeach