【问题标题】:belogs to many Relation between 3 entities laravel属于 3 个实体 laravel 之间的许多关系
【发布时间】:2020-07-20 10:06:56
【问题描述】:

我有 3 个实体类别、帖子和页面。 Category 和 Post 之间的关系属于 many(并且工作正常),Page 和 Category 之间的关系也属于 many(它也工作正常)。现在我想检索页面中所有类别的帖子。有没有办法在页面和帖子之间建立直接关系? 我的表格结构:

categories: int id string title.

posts: int id text content.

categories_posts: int id int category_id int post_id.

pages: int id string title.

pages_categories: int id int page_id int category_id.

【问题讨论】:

  • 这有点棘手,您可以尝试以下代码吗? class Page extends Model { public function posts() { return $this->hasManyThrough( 'App\Post', 'App\PagesCategory', 'category_id', // Foreign key on pages_categories table... 'id', // Foreign key on posts table... 'id', // Local key on pages table... 'user_id' // Local key on pages_categories table... ); } }
  • 我已经尝试过了,但是没有用。

标签: laravel eloquent laravel-5.8 eloquent-relationship


【解决方案1】:

我认为“加入”链会达到目的

在页面模型中:

public function posts()
{
return $this->join('pages_categories','pages_categories.page_id','=','pages.id')
->join('categories','categories.id','=','pages_categories.category_id')
->join('categories_posts','categories_posts.category_id','categories.id')
->join('posts','categories_posts.post_id','posts.id')->select('posts.*');
}

【讨论】:

  • 感谢您的回答。连接链不会很慢?
  • 我加入是连接表的更快方法......我不认为有更快的方法来做到这一点
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多