Laravel,显示所有Id匹配的数据
Laravel, display data where all Ids are matched
在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
}
]
}
如何 return 与 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();
它有效,但它只显示第一个匹配项。
任何帮助表示赞赏。
您可以使用 pluck 来获取 ID。
$newsIds = DB::table('content_pack_news')
->where('content_pack_id' , $content_pack_id)
->pluck('news_id');
Pluck 与 whereIn()
结合使用时效果很好,可根据数组检查列。
$news = News::with(['media', 'assigned_content_packs'])
->whereIn('id' , $newsIds)
->get();
您可以使用子查询在单个查询中执行此操作:
$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();
如果我纠正你只问第一个。
$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();
在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
}
]
}
如何 return 与 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();
它有效,但它只显示第一个匹配项。 任何帮助表示赞赏。
您可以使用 pluck 来获取 ID。
$newsIds = DB::table('content_pack_news')
->where('content_pack_id' , $content_pack_id)
->pluck('news_id');
Pluck 与 whereIn()
结合使用时效果很好,可根据数组检查列。
$news = News::with(['media', 'assigned_content_packs'])
->whereIn('id' , $newsIds)
->get();
您可以使用子查询在单个查询中执行此操作:
$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();
如果我纠正你只问第一个。
$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();