亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當 {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 關注
  • 90 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號