首页 > 解决方案 > 使用 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);
        }
    });
}

标签: laraveleloquent

解决方案


我建议使用Laravel 集合来建立雄辩的关系。

$comments = Comment::with('user', 'confirmerUser', 'product')->get();
$comments = collect($comments)->sortBy($sort_by)->splice(5);

使用sortBy()sortByDesc()进行排序,使用splice()进行分页

希望这可以帮助。干杯!


推荐阅读