skip to Main Content

I am having trouble getting a number instead of a string in my query. I have two tables and a pivot table.

File:

  • id
  • name
  • document
  • language

Role:

  • id
  • name (admin, partner, dealer, associate)

File_role:

  • id
  • file_id
  • role_id

I want to display all the files for the ‘dealer’ role so i tried this:

$file_role = File_Role::where('role_id', '=', $id)->get('file_id');
$file = File::where('id', '=', $file_role)->get();
dd($file_role);

However it keeps returning errors on:

$file = File::where('id', '=', $file_role)->get();

The error is:

SQLSTATE[HY093]: Invalid parameter number.

The query below that is:

select * from `file` where `id` = {"file_id":1}.

Any ideas how I can get a number instead of "file_id":1?

2

Answers


  1. You can give this a try. Here you get the first result and then get the file_id from that model.

    $file_role = File_Role::where('role_id', '=', $id)->firstOrFail();
    $file = File::where('id', '=', $file_role->file_id)->get();
    
    dump($file_role);
    dd($file);
    
    Login or Signup to reply.
  2. I think you are trying to use whereIn:

    $file_role = File_Role::where('role_id', '=', $id)->pluck('file_id');
    $file = File::whereIn('id', $file_role)->get(); 
    

    Other than just solving your issue I think there’s some more things you can consider here:

    File_Role seems to be a pivot table model. Generally you should not have these models as models in your app but rather define relationships for example in your File.php model file:

    public function role() {
       return $this->belongsToMany(Role::class);
    }
    
    

    This way your code becomes the (arguably) more readable:

    $file = File::whereHas('role', fn ($query) => $query->where('id', $id));
    

    This will result in all files that have a role with id given by $id

    More on many to many relationships

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search