#Can you guys teach me how to load relations for when using Model::cursor()?

6 messages · Page 1 of 1 (latest)

fallow parcel
#

On Document this is how to use

User::with([
    'posts' => function ($query) {
        $query->where('status', 'published');
    },
    'profile',
    'roles.permissions'
])->cursor()->each(function ($user) {
    // Process user with filtered posts, profile, and nested role permissions
    foreach ($user->posts as $post) {
        echo "Processing post: {$post->title}" . PHP_EOL;
    }
});

but What i want to do is cant we just load all relations into cursor without each loading $user->posts ??

odd crypt
#

-# [WRONG ANSWER]

with that code the posts should be loaded without using $user->posts.

try this:
User::with('posts')->cursor()->each(function ($user) {
~~ dd($user);~~
});

the posts attribute should be a collection. compared to this:
User::cursor()->each(function ($user) {
~~ dd($user);~~
});

the posts attribute should be null.

fervent ruin
#

I don't know if it has been changed since, but last I checked, cursor() doesn't support eager loads with extra constraints. I had to switch to chunkById() to get it to work.

bronze dew
#

Yeah, Mono is right

Since the cursor method only ever holds a single Eloquent model in memory at a time, it cannot eager load relationships. If you need to eager load relationships, consider using the lazy method instead.
https://laravel.com/docs/13.x/eloquent#cursors

odd crypt
#

my bad

fallow parcel
#

Oh nyo...😢😢 why cant it load eager load whyy