Php Laravel从不同的ID获取所有行
今天我只是在练习我的技能,被卡住了。我只想使用特定的ID从数据库中获取数据,这些ID作为数组放在会话中。问题是,我找不到一种方法来获取包含这些ID的所有数据。 这是我的购物车结账方法Php Laravel从不同的ID获取所有行,php,laravel,eloquent,Php,Laravel,Eloquent,今天我只是在练习我的技能,被卡住了。我只想使用特定的ID从数据库中获取数据,这些ID作为数组放在会话中。问题是,我找不到一种方法来获取包含这些ID的所有数据。 这是我的购物车结账方法 public function checkout(){ $uniqid = session('products'); $post=Post::find($uniqid); return view('pages.checkout')->with('post',$post); } 我
public function checkout(){
$uniqid = session('products');
$post=Post::find($uniqid);
return view('pages.checkout')->with('post',$post);
}
我没有得到任何数据,即使我试图得到一些数据,但当有7个字段时,我只得到一个字段。
这是会话产品阵列
0 "15be4aa3b55f10"
1 "15be4814ceb2a0"
2 "15be4814ceb2a0"
3 "15be4aa3b55f10"
4 "15be4aa3b55f10"
5 "15be4aa3b55f10"
6 "15be4aa3b55f10"
7 "15be4aa3b55f10"
find
查询返回一行数据。如果要获取多个数据,请使用all
查询:
$post = Post::all();
$post = Post::where('column_name', $uniqid)->get();
或者,如果要获取与$uniqid
具有相同id的所有数据,请使用where
查询:
$post = Post::all();
$post = Post::where('column_name', $uniqid)->get();
编辑
如果会话有多个id,您可能希望循环并查找与您的$uniqid
id相同的所有数据
public function checkout(){
$products = [];
foreach(session('products') as $session){
$post=Post::find($session->id);
$products[] = $post;
}
return view('pages.checkout')->with('products ',$products);
}
你可以试试这个:
public function checkout(){
$uniqid = session('products');
$products = Post::whereIn('unique_id', $uniqid)->get();
return view('pages.checkout')->with('products',$products);
}
其中,方法采用字段名和值数组
来自laravel:
其中方法验证给定列的值是否包含在给定数组中
应该使用where()方法根据多个ID获取记录。你喜欢这样吗
public function checkout(){
$uniqidsArray= session('products');
$post=DB::table('yourTableName')
->whereIn('id', $uniqIdsArray)
->get();
return view('pages.checkout')->with('post',$post);
}
是否可以添加dd(会话(“产品”)的结果;对于您的问题。您使用的是
find
它将只返回1个值。您可以对每个会话值进行设置,然后使用collection,就可以得到所有结果。当您返回它时,$uniqid
是什么样子的?这样做就成功了!公共函数checkout(){$products=[];foreach(session('products')as$session){$post=post::where('unique_id',$session)->get();$products[]=$post;}返回视图('pages.checkout')->with('products',$products);}感谢所有id必须存储在数组中,然后才能使用where()方法