skip to Main Content

Im currently using the SpatieMediaLibrary for my reviews model.

I got a query getting all reviews but im trying to show reviews that has images first using orderBy.

appModelsProduct.php Not working

public function reviews(): IlluminateDatabaseEloquentRelationsHasMany
    {
        return $this->hasMany(Review::class)->orderBy('media');
    }

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘media’ in ‘order clause’

Using has ‘media’ or doesnthave ‘media’ works. But I would like in the 1 query.

public function activeImageReviews(): IlluminateDatabaseEloquentRelationsHasMany
    {
        return $this->hasMany(Review::class)->has('media');

2

Answers


  1. If there exists a column called ‘media’ in the database you mig try:

    public function reviews(): IlluminateDatabaseEloquentRelationsHasMany
    {
        return $this->hasMany(Review::class)->orderByRaw('CASE WHEN `media` IS NULL THEN 0 ELSE 1 END ASC');
    
    }
    
    Login or Signup to reply.
  2. Unknown column 'media' implies that the column is not created in the table, make sure your migration is properly created.

    In other case, if your media is from a normalized, then your approach is supposed to be creating the relation between your Review model and your Media model then making the relation using with()

    return $this->hasMany(Review::class)->with('media')->orderBy('media.column');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search