#Eloquent request to get second degree relationship

3 messages · Page 1 of 1 (latest)

floral trail
#

Hi everyone, I have a piece of code that I'd like to simplify with a better Eloquent request.

Here's what I have so far:

$localPrices = LocalPrice::whereNotNull('error')
  ->whereRelation('product', 'monitored', true)
  ->get();

$errors = [];
foreach($localPrices as $localPrice) {
  if($localPrice->product->client->environment == 'prod') {
    $errors[] = [
        'environment' => $localPrice->product->client->environment,
        'client' => $localPrice->product->client->client_display_name,
        'country' => $localPrice->country->name,
        'product' => $localPrice->product->name,
        'error' => $localPrice->error,
    ];
  }
}

The LocalPrice model has two foreign keys: product_id, country_id.
The Product model has one foreign key: country_id.

I would like to update my request to only get LocalPrice that are related to a **product **that are related to a **client **whose environment is 'prod'.
I'd like to avoid the if() part but I don't know how to get this "second degree" relationship.

Could you please point me to the right direction? Thanks!

unreal steeple
#

Hello @floral trail,

You are right, you should avoid using the if statement, you are loading extra data. Let the database filter for you.

To answer your question, I think you could do this:

LocalPrice::query()
  ->whereNotNull('error')
  ->whereRelation('product', funtion($query){
    $query
      ->where('monitored', true)      
      ->whereRelation('client', 'environment', 'prod');
  })
floral trail