【发布时间】:2021-11-15 03:02:51
【问题描述】:
我有三个表:products、product_inventories 和 product_inventory_details。各型号的ORM如下图,
产品型号
class Product extends Model{
...
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
...,
'title',
'selected_inventory_id',
...
];
/**
* Get the inventories those belongs to this model.
*/
public function inventory(){
return $this->hasMany('App\Models\ProductInventory');
}
/**
* Get the selected product_inventory_detail that owns this model.
*/
public function selected(){
return $this->hasOne('App\Models\ProductInventoryDetail', 'id', 'selected_inventory_id');
}
...
}
产品库存模型
class ProductInventory extends Model{
...
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'product_id',
...
];
/**
* Get the inventory_details those belongs to this model.
*/
public function items(){
return $this->hasMany('App\Models\ProductInventoryDetail');
}
...
}
ProductInventoryDetail 模型
class ProductInventoryDetail extends Model{
...
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'product_inventory_id',
'price',
...
];
}
我通过排序方式下拉列表和每页显示下拉列表的用户输入对结果进行排序和限制。当按 Alphabetical: High to Low 选项排序时,我正在运行 query builder 方法来排序结果:
$products = $products->orderBy($sort['column'], $sort['order'])->paginate($limit);
现在按价格排序,我无法运行查询构建器方法orderBy(),因为我没有使用连接并通过关系属性获取数据。相反,我使用 Laravel 的 collection 方法对其进行排序:
$products = $products->paginate($limit);
$products = $products->sortBy(function($prod, $key){
return $prod->selected->price;
});
如果我不使用分页方法,上述块工作正常。但是,我还需要使用pagination,因为用户还可以限制每页的结果。我还使用Paginator 对象的方法将一些参数附加到每个页面 URL:
$products->appends($paramsArr);
由于运行sortBy() 方法返回一个集合而不是Paginator 对象,它给了我undefined method 异常。
我的问题
如何在当前场景中按价格对结果集进行排序,而无需实现联接?有没有办法做到这一点??
【问题讨论】:
标签: php mysql laravel eloquent laravel-8