Laravel 负载与模型条件的关系

Rob*_*man 7 php sql laravel eloquent

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

$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();
Run Code Online (Sandbox Code Playgroud)

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

lin*_*ref 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');
    }
});
Run Code Online (Sandbox Code Playgroud)