gpt4 book ai didi

php - 如何在laravel中使用多个键和值从数据库中查询数据?

转载 作者:行者123 更新时间:2023-11-29 15:23:03 25 4
gpt4 key购买 nike

我已经尝试过,但它返回空数组。

    $arr = [];
foreach($request->spec_id as $key=>$id){
$arr[$id] = $request->spec[$key];
}

$arr = array_filter($arr);

Ex: $arr = [
6 => "2000",
9 => "Petrol"
];

$data = DB::table('categories as c')
->join('postads as p','c.id','p.category_id')
->join('postad_specifications as ps','p.id','ps.postad_id')
->join('specifications as s','ps.specification_id','s.id')
->where('p.category_id',$request->category_id)
->where(function($query) use($arr){
foreach($arr as $key=>$value){
$query->where('ps.specification_id',$key);
$query->where('ps.value',$value);
}
})
->select('p.id','p.ad_title')
->distinct()
->get();

我想要的结果来自 postads 表,其中 ps.specation_idps.value 与键和值匹配。我该如何解决这个问题?

最佳答案

您可以使用 array_keys、array_values 函数,并在 Laravel 中使用 whereIn

    $arr = [];
foreach($request->spec_id as $key=>$id){
$arr[$id] = $request->spec[$key];
}

$arr = array_filter($arr);

Ex: $arr = [
6 => "2000",
9 => "Petrol"
];

$arrKeys = array_keys($arr);
$arrValues = array_values($arr);

$data = DB::table('categories as c')
->join('postads as p','c.id','p.category_id')
->join('postad_specifications as ps','p.id','ps.postad_id')
->join('specifications as s','ps.specification_id','s.id')
->where('p.category_id',$request->category_id)
->whereIn('ps.specification_id', $arrKeys)
->whereIn('ps.value', $arrValues)
->select('p.id','p.ad_title')
->distinct()
->get();

关于php - 如何在laravel中使用多个键和值从数据库中查询数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com