r/PHPhelp•
mrthesis

Laravel: Can I somehow only hydrate models once per unique instance?

I have a many-to-many relationship, currently with about 2.5k rows in one and 100 rows in the other (think Posts/Tags). Each Post has about 3 tags. This leads to my pivot table having 7.5k rows.

When trying to do $posts = Post::with('tags')->get();debug bar tells me it hydrated 10000 models (2500 + 7500). Can I somehow change this to only hydrate 2600 (2500 + 100)? Each tag only needs to be loaded once.

I'm guessing its because of the loading of the pivot/bridging table data, but I'm in a purely display scenario, so there is no need to do syncand such.

Otherwise, I guess it's time to look into pagination on server side, was hoping to keep that on client side for now (via Datatables).

Posted Feb 29, 2020, 9:11 AM UTC

33
koalam0•

https://laravel.com/docs/6.x/eloquent-relationships#lazy-eager-loading

maybe this, it doesn’t seem to say anything about not being able to constrain it with a limit or take so maybe try that

or pagination

1
[deleted]•

[deleted]

1
self_aware_machine•

Hydrating models is basically adding data to an object. If you load the pivot table then it will to having a high hydration count. Unless you are calling your tags table with a N+1 query.

Pagination is your best friend here.

1
TheRealBeakerboy•

As someone who knows a bit about PHP, I’m guessing this is a framework question. What framework are you working in? I’ve never heard the term “hydrate” before in PHP programming...and Pivot tables to me are those things I never use (but the accounting team loves) in Microsoft Excel.

-3