【问题标题】:Laravel Load Relation With Condition On ModelLaravel 负载与模型条件的关系
【发布时间】:2020-11-24 02:13:37
【问题描述】:

我正在尝试使用取决于通知模型值的关系来急切加载用户的通知:

$notifications = $user->notifications()
    ->with([
        'notifiable' => function ($query) {
            // Only load notifiable relation if notification 'notifiable_type' equals...
        },
        'notifiable.group:id,title' => function ($query) {
            // Only load notifiable.group:id,title relation if notification 'notifiable_type' equals... 
        }
    ])
    ->get();

问题是闭包中的$query 正在查询notifiable 关系而不是通知模型本身......我显然错过了一些非常微不足道的东西。有什么建议吗?

【问题讨论】:

标签: php sql laravel eloquent


【解决方案1】:

你可以使用Lazy Eager Loading

$notifications = $user->notifications;

$notifications->each(function ($item) {
    if ($item->notifiable_type == 'value-one') {
        $item->load('notifiable');
    }

    if ($item->notifiable_type == 'value-two') {
        $item->load('notifiable.group:id,title');
    }
});

【讨论】:

  • 不错!通过检查$this->notifiable_type 和延迟加载,我在通知模型的 API 资源中做了类似的事情,但是我更愿意将该逻辑保留在 API 资源之外。不敢相信我没有想到这个!
猜你喜欢
  • 2020-10-26
  • 2017-07-26
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
相关资源
最近更新 更多