php - Laravel Eloquent whereIn with where inside relationship
I have an relationship structure like this:
PlacehasMany
ServiceService
belongsTo
ServiceType
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
Answer
Solution:
To query relationships, you need to use the specific functions available for that. You're looking for the
whereHas()
method.You can read more about querying relationships here.