问题描述
我正在做Laravel任务,我想对与另一个表相关的表进行排序。 我在这里阅读该文档:https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models 我的代码:
$addonCategories = AddonCategory::withCount('addons')->sortable()->orderBy('id','DESC')->with('addons')->paginate(20);
return view('admin.addonCategories',array(
'addonCategories' => $addonCategories,));
AddonCategory控制器:
class AddonCategory extends Model
{
use Sortable;
protected $casts = ['addons_count' => 'integer'];
public $sortable = ['name','type','addons_count','created_at'];
public function items()
{
return $this->belongsToMany(Item::class);
}
public function addons()
{
return $this->hasMany('App\Addon');
}
}
addonCategories.blade.php:
<th>@sortablelink('addons_count',__('storeDashboard.acpTableNOA'))</th>
当我使用sortable时,会发生错误
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'addons_count' in 'order clause'
我认为这是因为数据库表中没有addons_count。那么如何用{relations} _count这样排序?
解决方法
首先,您似乎正在使用以下库:https://github.com/Kyslik/column-sortable
您的$sortable
中的AddonCategory
属性将数组元素与表的列名匹配。
因此,您收到错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'addons_count' in 'order clause'
鉴于MySQL表addons_count
中没有addon_category
列,并由laravel作为属性添加,您需要实现Aliasing
,该列在{ {3}}
您的最终模型将为:
class AddonCategory extends Model
{
use Sortable;
protected $casts = ['addons_count' => 'integer'];
public $sortable = ['name','type','created_at'];
public $sortableAs = ['addons_count'];
public function items()
{
return $this->belongsToMany(Item::class);
}
public function addons()
{
return $this->hasMany('App\Addon');
}
}
实施的其余部分很好。