为了账号安全,请及时绑定邮箱和手机立即绑定

当 {relations}_count 不在数据库表中时如何对 {relations}

当 {relations}_count 不在数据库表中时如何对 {relations}

PHP
Cats萌萌 2023-10-01 15:42:14
我正在执行 Laravel 任务,我想对与另一个表相关的表进行排序。我在这里阅读了文档: https: //laravel.com/docs/5.4/eloquent-relationships#counting-lated-models 我的代码:$addonCategories = AddonCategory::withCount('addons')->sortable()->orderBy('id', 'DESC')->with('addons')->paginate(20);return view('admin.addonCategories', array(            'addonCategories' => $addonCategories,        ));插件类别控制器: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 进行排序呢?
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

首先,您似乎正在使用该库: https: //github.com/Kyslik/column-sortable

$sortable您中的属性与数组AddonCategory元素和表的列名相匹配。因此,您收到错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'addons_count' in 'order clause'

addons_count鉴于MySQL 表中不存在该列addon_category,并且由 laravel 作为属性添加,您需要实现Aliasing,这是在库的文档中指定的

您的最终模型将如下:

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');

    }

}

其余的实施都很好。

查看完整回答
反对 回复 2023-10-01
  • 1 回答
  • 0 关注
  • 41 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信