Search code examples
laraveleloquentlaravel-7eloquent-relationship

Laravel Eloquent get model with double belongsTo relationship


I'm having a Model ToGoSubscriptions with belongsTo relationship to two other models, PhoneNumber and ToGoDevice.

Both PhoneNumber and ToGoDevice haveMany ToGoSubscription.

I have a PhoneNumber and a ToGoDevice, what I need to do is retrieve a ToGoSubscription that belongs to the given PhoneNumber and ToGoDevice. This should always be a single record if everything works fine.

Relationships Image

These are relevant columns I have in each table:

phone_numbers table:

id
name            
number          
description

to_go_devices table:

id
name            
mac         
IP

to_go_subscriptions table:

id
phone_number_id         
to_go_subscription_type_id      
to_go_device_id     
expiry_date

So far I have tried these 2 snippets but the results I get are not desirable.

ToGoSubscription::where('phone_number_id', $phoneDetails->id)->with(['toGoDevice' => function($q){
        $q->where('to_do_devices.id', '=',  $deviceId);
    }])->get();

and

 $phoneDetails->toGoSubscription($deviceDetails->id)->get();

All I need is to get the one subscription that belongs to the $phoneNumber and to the $mac I have. I'm able to get the $phoneDetails from the phone_numbers table and $deviceDetails using $mac from to_go_devices table.

I'm really not able to wrap my head around the eloquent way of getting the subscription that belongs to the PhoneNumber and ToGoDevice I have. Some help here will be really appreciated.


Solution

  • you can use a chain of where:

    $value= ToGoSubscription:: where('phone_number_id', $phoneDetails->id)->where('to_go_device_id', $deviceId) ->get();