adam78
adam78

Reputation: 10068

Laravel 5.2 - Query Builder Syntax To Filter Polymorphic Relationship?

I have the following query where I want to filter a polymorphic relationship:

$companyLogo = $user->company->files->where('file_type', 'Logo')->first();

When I enable the query log this is what I get:

"query" => "select * from `files` where `files`.`fileable_id` = ? and `files`.`fileable_id` is not null and `files`.`fileable_type` = ?"
"bindings" => array:2 [▼
  0 => 1
  1 => "App\Company"
]

As you can it is not including my where clause?

* Update *

This is the polymorhpic relationship I have between company and file models:

class File extends Model {

    protected $fillable = [
    'name',
    'path',
    'size',
    'mime_type',
    'file_type',
    'fileable_id',
    'fileable_type',

   ];

   public function fileable()
   {
       return $this->morphTo();
    }

}


class Company extends Model {

   public function files()
   {
       return $this->morphMany('App\File', 'fileable');
   }

 }

I'm not sure why the query inst including the where clause either. Is the syntax correct to filter a polymorphic relationship? A company can have different types of files e.g. documents, logo etc but I want to select the logo.

Upvotes: 1

Views: 1493

Answers (1)

adam78
adam78

Reputation: 10068

I decided to refactor as follows:

Added a query scope to the File class:

public function scopeCompanyLogo($query, $id)
{
    $query->where('file_type','=', 'Logo')
        ->where('fileable_type','=', 'App\Company')
        ->where('fileable_id','=', $id);
}

Now get the company logo as follows:

 $companyLogo = File::CompanyLogo($user->company_id)->first();

* Update *

Just figured what was wrong with original code too

Instead of doing this:

$companyLogo = $user->company->files->where('file_type', 'Logo')->first();

It should have been:

 $companyLogo = $user->company->files()->where('file_type', 'Logo')->first();

Upvotes: 1

Related Questions