laravel - 使用 Eloquent 不加入按相关表的文件排序
问题描述
我使用 Eloquent 方法来处理表格。我没有使用查询和连接。只是与 hasMany 和 belongsTo 建立关系。而且我不想使用连接和查询。我应该根据某些字段对结果进行排序。对主表字段进行排序没有任何问题。但是当我想按相关的表字段排序时,我得到了错误。
请求网址: http://localhost:8000/admin/pagination/fetch_data?page=1&sortby=product.product_title&sorttype=asc
请求方法:GET 状态码:500 内部服务器错误
这是我的代码。
评论
class Comment extends Model
{
public function user()
{
return $this-> belongsTo('App\User', "comment_userid");
}
public function confirmerUser()
{
return $this-> belongsTo('App\User', "comment_confirmeruserid");
}
public function product()
{
return $this->belongsTo("App\Product", "comment_productid");
}
}
产品
class Product extends Model
{
public function comments()
{
return $this->hasMany('App\Comment', "comment_productid");
}
}
用户
class User extends Authenticatable
{
public function comments()
{
return $this->hasMany('App\Comment', "comment_userid");
}
public function comments_confirmer()
{
return $this->hasMany('App\Comment', "comment_confirmeruserid");
}
}
在控制器中
public function controller_fetch_data(Request $request)
{
if( $request->ajax() ) {
$sort_by = $request->get('sortby');
$sort_type = $request->get('sorttype');
$comments = Comment::with('user', 'confirmerUser', 'product')
->orderBy($sort_by, $sort_type)->paginate(5);
$p_pagenumber = $request['page'];
return view("adminPanel.comment_list")
->with('p_pagenumber', $p_pagenumber)
->with('comments', $comments)
->render();
}
}
在视图中
function fetch_data(page, sort_type, sort_by)
{
$.ajax({
url : "/admin/pagination/fetch_data?page=" + page + "&sortby=" + sort_by + "&sorttype=" + sort_type,
success : function(data) {
$("#table_data").html('');
$("#table_data").html(data);
}
});
}
解决方案
我建议使用Laravel 集合来建立雄辩的关系。
$comments = Comment::with('user', 'confirmerUser', 'product')->get();
$comments = collect($comments)->sortBy($sort_by)->splice(5);
使用sortBy()或sortByDesc()进行排序,使用splice()进行分页
希望这可以帮助。干杯!
推荐阅读
- ios - 为什么将无法识别的选择器发送到实例?
- html - 如何在ios浏览器中使禁用的输入按钮不是“灰色”?
- java - Spring Boot 和混淆代码 Proguard
- javascript - 如何使用硒在 Youtube 中向下滚动?
- javascript - 如何使用 node.js 中的另一个数据处理获取的数据?
- python - Python3 psycopg2:使用返回“没有要获取的结果”
- c++ - 从具有指向 char 数组的指针的数组中为 String 赋值
- ansible - 使用 Ansible playbook 时出错。错误消息:“msg”:“此模块需要 boto”
- xml - 从 Biztalk 可视化地图中的单个输入节点的范围创建多个输出节点
- hyperledger-fabric - Hyperledger Fabric:使用 memberOnlyRead 功能查询私有数据