【问题标题】:How to get post which have multiple table relationship?如何获取具有多个表关系的帖子?
【发布时间】:2019-11-17 14:27:29
【问题描述】:

我的数据库架构

表 POST

| id | title | content |

表共享组

|id | title | slug 

表 Post_SharedGroup

|id| post_id | shared_group_id|

我想在 laravel 中查询我给 sharedgroup 的 slug 并发布它

【问题讨论】:

  • 请在预期输出中添加示例输入数据。
  • 我有 slug 共享组,我想要它的相关帖子

标签: laravel laravel-5 eloquent many-to-many relationship


【解决方案1】:
$data = Post::whereHas('sharedGroup',function($query) use($slug){
        $query->whereIn('slug',$slug);
       })->get();

$slug 是你提供的 slug 数组

模特帖

public function sharedGroup(){
    return $this->belongsToMany('App\SharedGroup');
}

模型共享组

public function post(){
    return $this->belongsToMany('App\Post');
}

【讨论】:

  • 我会给多个蛞蝓不只是一个,我想返回帖子
  • 用户 whereIn() 而不是 where()... 我更新了答案
  • 我想返回 Post Model 而不是 SharedGroup
【解决方案2】:

您似乎只想要三个表之间的基本连接:

$posts = DB::table('POST p')
    ->join('Post_SharedGroup ps', 'p.id', '=', 'ps.post_id')
    ->join('SharedGroup s', 'ps.shared_group_id', '=', 's.id')
    ->whereIn('s.slug', array(1, 2, 3))  // match slug values (1, 2, 3)
    ->select('p.*')
    ->get();

【讨论】:

  • 我想给多个 sharedgroup slugs
  • @RevTech 然后使用 Laravel 的 whereIn() 函数,并传入一个匹配 slug 值的数组。
  • 可以不加入吗?
  • 请注意,我知道...也许框架有隐藏连接的方法,但连接肯定会在 MySQL 数据库的底层发生。
猜你喜欢
  • 2015-05-24
  • 1970-01-01
  • 2021-01-30
  • 2012-02-26
  • 2023-03-12
  • 2016-11-10
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
相关资源
最近更新 更多