Laravel雄辩的三元关系与枢轴

时间:2019-09-27 16:02:40

标签: laravel eloquent relationship

我正在尝试用数据透视表在3个表之间建立关系。由于count()方法,我只想雄辩地说。

这是我的桌子。

brands: id, name
posts: id, title
tags: id, name, brand_id (fk)
post_tag: post_id (fk), tag_id (fk)

说明:

  • 品牌有很多通过标签发布的信息
  • 标签属于品牌
  • 品牌应通过标签从数据透视表中选择post_id以获得正确的帖子。

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

这正是我真正想做的:

  • 首先,我在创建帖子时获取标签名称并在brands表中搜索以获取它。之后,我将帖子从透视表分配给标签,以在帖子/索引页面上创建列表。标签属于品牌;在这一点上,我想获得品牌并展示其属性。另外,我还需要能够按模型$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

0 个答案:

没有答案