雄辩的查询:所有具有相同类别的新闻。数据透视表

时间:2019-06-07 07:59:09

标签: laravel eloquent pivot-table relationship

我需要在Eloquent查询中获取与特定新闻具有相同(一个或多个)类别的所有新闻。而且我不了解数据透视表。

我有3张桌子:

新闻

ant design

NewsxCategory (数据透视表)

id | title | content

新闻类别

news_id | category_id

口才模式

id | name

我尝试过这个。

在助手中:

// NewsCategory model
class NewsCategory extends Model
{

}

// News Model
class News extends Model
{

    public function categories()
    {
        return $this->belongsToMany(NewsCategory::class, 'news_x_category', 'news_id', 'category_id');
    }

}

在视野中:

/**
 *  only related news
 *
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function relatedNews(News $new)
{
    $categories = $new->categories(); //obtain all categories of $new

    return News::whereHas('categories', function ($query) use ($categories) {
        $query->whereIn('new_id', $categories);
    });
}

但是助手总是返回<div class="related-articles"> <h5>{{ __('RELATED ARTICLES') }}</h5> <ul class="articles"> @foreach ( App\Helpers\News::relatedNews($newsItem) as $new) <li> <h6>{{ $new->title }}</h6> <p>{{ $new->publication_date }}</p> </li> @endforeach </ul> </div>

我也在助手中尝试过

null

但是此选项返回所有新闻。

我需要所有与新闻相关的信息,我的意思是具有相似类别的新闻。数据透视表让我头疼。

谢谢!

1 个答案:

答案 0 :(得分:2)

whereIn子句中,您需要传递ID数组。但是你没有通过正确。

这是正确的。

/**
 *  only related news
 *
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function relatedNews(News $new)
{
    $categoryIds = $new->categories->pluck('category_id')->toArray(); //obtain all categories of $new

    return News::whereHas('categories', function ($query) use ($categoryIds) {
        $query->whereIn('category_id', $categoryIds);
    });
}

我认为在更改之后,上述功能也会发生变化。您将获得相关新闻。

已更新

如果您要打印相关新闻,请使用此:

@foreach ( App\Helpers\News::relatedNews($newsItem)->get() as $new)
    {{ $new->title }}
@endforeach
相关问题