Laravel Eloquent 获取具有双重 belongsTo 关系的模型

Laravel Eloquent get model with double belongsTo relationship

我有一个模型 ToGoSubscriptions 与另外两个模型 PhoneNumber 和 ToGoDevice 有 belongsTo 关系。

PhoneNumber 和 ToGoDevice 都有很多 ToGoSubscription。

我有一个 PhoneNumber 和一个 ToGoDevice,我需要做的是检索属于给定 PhoneNumber 和 ToGoDevice 的 ToGoSubscription。如果一切正常,这应该始终是一条记录。

这些是我在每个 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

到目前为止,我已经尝试了这 2 个片段,但我得到的结果并不理想。

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

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

我只需要获得属于 $phoneNumber 和我拥有的 $mac 的一个订阅。我可以使用来自 to_go_devices table.

的 $mac 从 phone_numbers table 获取 $phoneDetails 和 $deviceDetails

我真的无法理解 eloquent 获取属于我拥有的 PhoneNumber 和 ToGoDevice 的订阅的方式。在这里提供一些帮助将不胜感激。

你可以使用一个链式 where:

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