[英]Using pivot table with Eloquent and Laravel
这是我的问题。 我有一个名为表news
和表叫categories
,我也有一个连接这两个所谓的透视表news_categories
。 我正在尝试从特定类别中获取最近的10篇文章,但是显然数据透视表没有时间戳。 我正在阅读有关hasMany(),beforeToMany()的文章,但没有找到一个很好的例子。 任何帮助表示赞赏
到目前为止,我已经对News模型执行了此操作:
public function categories(){
return $this->has_many_and_belongs_to("Categories")->withPivot('category_id', 'news_id');
}
但我不知道如何根据category_id
数据透视表值选择新闻
您可能想稍微阅读一下Laravel 4 Eloquent文档 ...
关系函数是错误的,您无需指定枢纽项目。 withTimestamps()
函数将自动为您管理数据透视表上的内容。
public function categories()
{
return $this->belongsToMany('Category')->withTimestamps();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.