为什么我的PHP代码中的orderBy方法不起作用?

为什么我的PHP代码中的orderBy方法不起作用?,php,laravel,Php,Laravel,我用Laravel5编写了这段PHP代码,orderBy无法工作 Route::get('/products',function (){$products= DB::table('products')->get(); return view('products.index',compact('products'));}); Route::get('/products/{id}',function ($id){$product= DB::table('products')->find

我用Laravel5编写了这段PHP代码,orderBy无法工作

Route::get('/products',function (){$products= DB::table('products')->get();
return view('products.index',compact('products'));});

Route::get('/products/{id}',function ($id){$product= DB::table('products')->find($id);
        return view('products.show',compact('product'));});
而index.blade.php代码是

 <div><a href={{"/products/".$product->id}}>{{$product->name}}</a></div>

而show.blade.php代码是:

 <h1>{{$product->name}}</h1>
 <p> {{$product->description}}</p>
{{$product->name}
{{$product->description}

当您使用
find()
时,它将只返回1个注册表。因此,按顺序排序没有效果

如果
$id
出现在多行中,则应使用
where
get()

因此,如果您添加order by,它应该可以工作:

Route::get('/products',function (){
    $products= DB::table('products')->orderBy('name','desc')->get();
    return view('products.index',compact('products'));
});

看起来很奇怪,您按一个字段排序,因为您可以找到表中的一个产品。可能DB::table('products')->orderBy('name','desc')->get();更有意义谢谢answar I编辑我的问题并用完全更改的内容完成code@TohidDa不要在回答之后编辑你的问题,除非你只是提供了更多的上下文。您已完全删除了orderBy呼叫。。。
Route::get('/products',function (){
    $products= DB::table('products')->orderBy('name','desc')->get();
    return view('products.index',compact('products'));
});