php - Laravel Eloquent whereIn with where inside relationship

693

I have an relationship structure like this:

PlacehasMany ServiceServicebelongsToServiceType

I'm trying to filter it byServiceType, but i always get a error trying various types saying that the table or view doesn't exist.

$place = Place::with('services.serviceTypes')->whereIn('id', $ids)
->where('services.serviceTypes.id', $id)->get();

or

$place = Place::with('services.serviceTypes')->whereIn('id', $ids)
->where('services.service_types.id', $id)->get();

returns the same exception.

Models:

Place:

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

class Place extends Model {  

    public function services(){
        return $this->hasMany('App\Service');
    }

}

Service:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Service extends Model {

    public function serviceType(){
        return $this->belongsTo('App\ServiceType');
    }


}

ServiceType:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ServiceType extends Model {

    public function services() {
      return $this->hasMany('App\Service');
    }
}

Thanks

612

Answer

Solution:

To query relationships, you need to use the specific functions available for that. You're looking for thewhereHas() method.

$place = Place::with('services.serviceTypes')
    ->whereIn('id', $ids)
    ->whereHas('services.serviceTypes', function ($query) use ($id) {
        return $query->where('id', $id);
    })
    ->get();

You can read more about querying relationships here.

People are also looking for solutions to the problem: php - How to safely sanitize / escape text in a wordpress widget input field (html capable)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.