Laravel,显示所有Id匹配的数据

r6hnlfcb  于 2022-12-01  发布在  其他
关注(0)|答案(3)|浏览(104)

controller index function中,我选择了哪些新闻ID与包ID匹配:

$content_pack_news_array = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->get();

使用dd得到这个结果,我需要访问其中所有元素的news_id

Illuminate\Support\Collection {#3017 ▼
  #items: array:2 [▼
    0 => {#2376 ▼
      +"news_id": 2
      +"content_pack_id": 2
    }
    1 => {#3010 ▼
      +"news_id": 4
      +"content_pack_id": 2
    }
  ]
}

如何返回与id匹配的数据:

"news_id": 2
"news_id": 4

内部:

$news = News::with(['media', 'assigned_content_packs'])->where('id' , $news_id)->get();

如果我用

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->first();

它工作,但它只得到第一个匹配的项目显示。任何帮助表示感谢。

kgsdhlau

kgsdhlau1#

你可以用pluck把身份证取出来。

$newsIds = DB::table('content_pack_news')
    ->where('content_pack_id' , $content_pack_id)
    ->pluck('news_id');

Pluck与whereIn()结合使用效果很好,whereIn()可以根据数组检查列。

$news = News::with(['media', 'assigned_content_packs'])
    ->whereIn('id' , $newsIds)
    ->get();
ltqd579y

ltqd579y2#

您可以使用子查询在单个查询中执行此操作,如下所示:

$news = News::with(['media', 'assigned_content_packs'])
                ->whereIn('id', function($query) use($content_pack_id){
                    $query->select('news_id')
                    ->from('content_pack_news')
                    ->where('content_pack_id', $content_pack_id);
                })
            ->get();
hgb9j2n6

hgb9j2n63#

如果我纠正你只问第一个问题。

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->first();

将其更改为get();那么您将获得所有记录。

$content_pack_news = DB::table('content_pack_news')->where('content_pack_id' , $content_pack_id)->get();

相关问题