Laravel + jquery 数据表中的 orderBy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38402902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
orderBy in Laravel + jquery datatables
提问by cyber8200
In my database, here is what I have
在我的数据库中,这是我所拥有的
I've tried to query everything and order by price
我尝试查询所有内容并按价格排序
$service_plans = DB::table('service_plans') ->orderBy('price', 'asc') ->get();
I kept getting
我一直得到
Did I miss anything or did anything that I'm not suppose to here ?
我是否错过了什么或做了什么我不应该在这里做的事情?
Any hints ?
任何提示?
P.S. Keep in mind that I'm using jQuery DataTables
PS 请记住,我使用的是 jQuery DataTables
回答by Mike Barwick
Since you're using Datatables jQuery plug-in, remove the orderBy
in your controller query.
由于您使用的是 Datatables jQuery 插件,因此请删除orderBy
控制器查询中的 。
Instead, sort via datatables (which will do so by default):
相反,通过数据表排序(默认情况下会这样做):
$('#datatable').DataTable({
"order": [[ 2, "asc" ]] // Order on init. # is the column, starting at 0
});
There's also a nice little Laravel package for datatables that will set the data. Check it and see if it'd be useful: https://github.com/yajra/laravel-datatables
还有一个很好的小 Laravel 数据表包,可以设置数据。检查它,看看它是否有用:https: //github.com/yajra/laravel-datatables
回答by swatkins
You can add a $casts
property to your ServicePlan
model. This will treat the column as the implicit data type regardless of the database data type.
您可以$casts
向ServicePlan
模型添加属性。无论数据库数据类型如何,这都会将该列视为隐式数据类型。
class ServicePlan extends Model
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'price' => 'integer',
];
}
https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting
https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting
回答by num8er
Type of price field is string so change it to decimal with 2 numbers after comma.
价格字段的类型是字符串,因此将其更改为逗号后有 2 个数字的十进制。
Run in mysql console:
在 mysql 控制台中运行:
ALTER TABLE service_plans MODIFY price DECIMAL(10,2);
!!! When making modification on tables on production make sure that You've copy of table before calling ALTER TABLE
:
!!!在生产中对表进行修改时,请确保您在调用之前已复制表ALTER TABLE
:
CREATE TABLE service_plans_bak AS SELECT * FROM service_plans;