laravel - 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();
但是这个选项会返回所有新闻。
我需要所有相关的新闻,我的意思是具有相似类别的新闻。数据透视表让我头疼。
提前致谢!
解决方案
在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
推荐阅读
- sql - 在 FROM 子句中使用 RIGHT JOIN 时出现无效标识符错误
- javascript - MongoNetworkError: connection 0 to localhost:27017 timed out .(不理解以前的解决方案)
- python - 如何修复该错误?“NoneType”对象没有属性“_root”
- javascript - 冻结 HTML 表格的多行和多列
- php - Magento 2 在购物车中添加自定义选项而不创建
- android - 未解决的参考。由于接收器类型不匹配,以下候选均不适用
- c# - double.ToString 截断最后 2 位数字,而我在调试时仍然可以看到它们
- vuejs2 - 我无法使用 VUE 注册我的服务人员
- python - 无法在熊猫中组合日期和时间
- ios - 如何使用 textContentType 在 React Native 中获取 iOS 的电子邮件自动完成建议?