Home > database >  cannot retrieve Category model with related items
cannot retrieve Category model with related items

Time:06-12

I have very strange error in my laravel website. I try to retrieve Category model with related items, but looking at the error I see that laravel tries to retrieve items field from category model and of course it fails. But I am completely cannot understand why it happens, because I have the same code working well in other parts of my website.

routes/web.php

Route::name('gallery.')->prefix('gallery')->group(function () {
    Route::get('/',       'GalleryController@index')->name('index');
    Route::get('/{slug}', 'GalleryController@item')->name('item');
});

GalleryController

    public function item($slug)
    {

        $category = $this->imageRepository->getCategoryWithPaginatedImages($slug, $perPage = 20);

        return view('pages.gallery.item', compact('category'));
    }

ImageRepository


namespace App\Repositories;

use Illuminate\Database\Eloquent\Collection;
use App\Models\ImageCategory as Model;


class ImageRepository extends CoreRepository
{

    protected function getModelClass()
    {
        return Model::class;
    }

    public function getCategoryWithPaginatedImages($slug, $perPage = null)
    {
        $columns = ['id','title','slug','description','image','published','metatitle','metakey','metadesc'];

        $result = $this
            ->startConditions()
            ->whereSlug($slug)
            ->select($columns)
            ->with('images:id,title,category_id,md,lg') 
            ->firstOrFail()
            ->toArray();

        $result = Arr::arrayToObject($result);
        $result->items = collect($result->items)->mypaginate($perPage);

        return $result;
    }

}

Image

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{

    protected $guarded = [];
    public function category() { return $this->belongsTo(ImageCategory::class); }

}

ImageCategory

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class ImageCategory extends Model
{

    protected $guarded = [];
    public    $timestamps = false;
    public function images() { return $this->hasMany(ImageCategory::class, 'category_id'); }
}

so when I hit gallery/slug then getCategoryWithPaginatedImages gives me following error

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_id' in 'field list' (SQL: select `id`, `title`, `category_id`, `md`, `lg` from `image_categories` where `image_categories`.`category_id` in (2))

CodePudding user response:

I guess the relationship images on ImageCategory definition has an issue, should be as under

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class ImageCategory extends Model
{

    protected $guarded = [];
    public    $timestamps = false;

    public function images() 
    { 
        return $this->hasMany(Image::class, 'category_id'); 
    }
}
  • Related