【问题标题】:Laravel Eloquent get model with double belongsTo relationshipLaravel Eloquent 获取具有双重 belongsTo 关系的模型
【发布时间】:2020-12-24 14:28:04
【问题描述】:

我的 ToGoSubscriptions 模型与其他两个模型(PhoneNumber 和 ToGoDevice)有关联。

PhoneNumber 和 ToGoDevice 都有很多 ToGoSubscription。

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

这些是我在每个表中的相关列:

电话号码表:

id
name            
number          
description

to_go_devices 表:

id
name            
mac         
IP

to_go_subscriptions 表:

id
phone_number_id         
to_go_subscription_type_id      
to_go_device_id     
expiry_date

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

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 的订阅。我可以从 phone_numbers 表中获取 $phoneDetails,并使用 $mac 从 to_go_devices 表中获取 $deviceDetails。

我真的无法用雄辩的方式获得属于我拥有的 PhoneNumber 和 ToGoDevice 的订阅。非常感谢这里的一些帮助。

【问题讨论】:

  • 为什么不只是:ToGoSubscription:: where('phone_number_id', $phoneDetails->id)->where('to_go_device_id', $deviceId) ->get();
  • 谢谢@OMR 我不知道我可以将 2 链接到哪里。我真是太丢人了!
  • 不客气,我会把我的评论作为答案,这样我们就可以认为这个问题已经解决了

标签: laravel eloquent laravel-7 eloquent-relationship


【解决方案1】:

你可以使用 where 链:

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

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 2017-01-12
    • 2018-08-06
    • 2018-03-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多