basanta/lazyloader

使用或不用关系懒加载 Laravel 模型。

1.0.2 2024-08-27 12:26 UTC

This package is auto-updated.

Last update: 2024-09-27 12:37:30 UTC


README

使用或不用关系懒加载 Laravel 模型。

use Basanta\LazyLoader\LazyLoader;

有多个

$usersWithClients = LazyLoader::make($users)->load(Client::class, 'clients')
    ->on([
        'clients.created_by' => 'id',
        'clients.assigned_to' => 'id'
    ])
    ->multi([
        'clients.email', 'clients.first_name', 'clients.last_name',
    ]);

有一个

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);

在何处

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->where('users.is_active', '=', 1)
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);

何时

$clientsWithUser = LazyLoader::make($clients)->load(User::class, 'user')
    ->on([
        'users.id' => [
            'created_by',
            'assigned_to'
        ]
    ])
    ->when(function($item) {
        // custom logic
        // lazy load user model only when missing
        return empty($item['user']);
    })
    ->single([
        'users.id', 'users.first_name', 'users.last_name',
    ]);