我有来自两个不同表的 2 个查询。第一个包含我想在第二个查询中使用的 ID。现在我这样做。我将 ID 提取到一个新数组中,然后在第二个查询的 ->whereIn()
中使用该数组。
$campaign = DB::connection('mysql2')->table('mc_spots')
->select('s_customer', 's_product', 'spotid')
->where('s_starttermin', '>=', date("Y-m-d", strtotime($dateFrom)))
->where('s_lastrun', '<=', date("Y-m-d", strtotime($dateUntil)))
->where('s_media', '=', $media)
->where(function ($query) use ($products) {
for ($i = 0; $i < count($products); $i++) {
$query->orwhere('s_product', '=', $products[$i]);
}
})
->get();
$campaignID = [];
foreach ($campaign as $c) {
array_push($campaignID, $c->spotid);
}
$table = DB::connection('mysql2')->table('schaltdaten_tv_de')
->select('*')
->join('epgdata_channel', 'schaltdaten_tv_de.cid', '=', 'epgdata_channel.channelid')
->join('mc_spots', 'schaltdaten_tv_de.ReferenceDescription', '=', 'mc_spots.spotid')
->whereIn('ReferenceDescription', $campaignID)
->groupBy('epgdata_2013.id')
->orderBy('StartofBreak', 'ASC')
->limit(500)
->get();
是否有更方便的方法来执行此操作,而无需循环遍历 $campaign
的每个项目?
最佳答案
您需要从第一个查询中提取id
,它为您提供了 id 数组,您可以在第二个查询中使用它。
$campaign = DB::connection('mysql2')->table('mc_spots')
->select('s_customer', 's_product', 'spotid')
->where('s_starttermin', '>=', date("Y-m-d", strtotime($dateFrom)))
->where('s_lastrun', '<=', date("Y-m-d", strtotime($dateUntil)))
->where('s_media', '=', $media)
->where(function ($query) use ($products) {
for ($i = 0; $i < count($products); $i++) {
$query->orwhere('s_product', '=', $products[$i]);
}
})
->pluck('spotid');
现在,在第二个 whereIn
中使用 spot id
数组,
$table = DB::connection('mysql2')->table('schaltdaten_tv_de')
->select('*')
->join('epgdata_channel', 'schaltdaten_tv_de.cid', '=', 'epgdata_channel.channelid')
->join('mc_spots', 'schaltdaten_tv_de.ReferenceDescription', '=', 'mc_spots.spotid')
->whereIn('ReferenceDescription', $campaign)
->groupBy('epgdata_2013.id')
->orderBy('StartofBreak', 'ASC')
->limit(500)
->get();
希望您能理解
关于php - 如何将一组 ID 从一个 Laravel 查询传递到另一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45277821/