[英]Why is the orderBy method in my PHP code not working?
我在 Laravel 5 中编写了这段 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>
当您使用find()
它只会返回 1 个注册表。 所以,order by 没有效果。
如果$id
出现在 1 行以上,那么您应该使用where
和get()
$product= DB::table('products')->where('id','=',$id)->orderBy('name','desc')->get();
因此,如果您添加 order by,它应该可以工作:
Route::get('/products',function (){
$products= DB::table('products')->orderBy('name','desc')->get();
return view('products.index',compact('products'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.