首页 > 解决方案 > Eloquent Query:所有具有相同类别的新闻。数据透视表

问题描述

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

我有 3 张桌子:

消息

id | title | content

NewsxCategory (数据透视表)

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

我也尝试过帮助:

return News::with('categories')->where('category_id',$categories )->get();

但是这个选项会返回所有新闻。

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

提前致谢!

标签: laraveleloquentpivot-tablerelationship

解决方案


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

推荐阅读