【问题标题】:Using pivot table with Eloquent and Laravel在 Eloquent 和 Laravel 中使用数据透视表
【发布时间】:2013-06-30 17:29:40
【问题描述】:

这是我的问题。我有一个名为news 的表和一个名为categories 的表,我还有一个连接这两个表的数据透视表,名为news_categories。 我正在尝试从某个类别中获取最后 10 篇文章,但显然数据透视表没有时间戳。 我正在阅读有关 hasMany()、belongToMany() 的信息,但没有找到一个很好的例子来说明它是如何完成的。任何帮助表示赞赏

到目前为止,我已经对 News 模型这样做了:

public function categories(){
    return $this->has_many_and_belongs_to("Categories")->withPivot('category_id', 'news_id');
}

但我不知道如何根据 category_id 的数据透视表值选择新闻

【问题讨论】:

  • 如果这是 Laravel 4,那么方法应该是 belongsToMany 而不是 has_many_and_belongs_to,因为这是 Laravel 3 的方法。

标签: php laravel laravel-4 eloquent


【解决方案1】:

您可能想稍微了解一下Laravel 4 Eloquent Documentation...

关系函数错误,不需要指定枢轴项。 withTimestamps() 函数会自动为您管理数据透视表上的内容。

public function categories()
{
    return $this->belongsToMany('Category')->withTimestamps();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    • 1970-01-01
    相关资源
    最近更新 更多