Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

If you've setup the belongsTo relationship between Post and Author, Eloquent will handle this for you automatically. For example:

$posts = Post::with('author')->all();

executed within your controller will retrieve the posts and will eager load the associated authors. Then, within your view, you could do:

@foreach ($posts as $post)
    {{ $post->author->author_name }}
@endforeach

For each of your Post models, the Author model will already be associated to it (assuming your belongsTo was defined within a method called 'author()').

Last updated 1 year ago.
0

When setting up the relationship, do I need to set up both ends of the relationship? For example, my Post model set up as belongsTo Author and also set up Author to hasMany Posts or will just the belongTo suffice? That does explain how Eloquent makes processing any data with a relationship easier though, thank you!

Last updated 1 year ago.
0

You only need the hasMany if you need to resolve something going the other way. In my above example, simply having the belongsTo defined within Post will work for that.

Note that the "with()" isn't required in that case, but when you include it, Eloquent will pull all relevant author information in with a single query (eager loading) rather than every iteration through your "foreach $posts" loop causing an additional query against your authors table. This is often referred to as the N+1 problem since a single query for 10 posts results in 11 queries (one for the posts and one for each author of each post).

Last updated 1 year ago.
0

Ah, I now have it working thank you so much! Eager loading is definitely what I had in mind, because iterating over 100 posts would clearly take a while if each resulted in a query, so thanks again.

One thing I had to change from your code example above, though, was

$posts = Post::with('author')->all();

to

$posts = Post::with('author')->get();

because it was returning "Call to undefined method Illuminate\Database\Query\Builder::all()". Not sure if I have something a little different on my end but it's working smoothly now!

Last updated 1 year ago.
0

I am following this thread to get my code running but getting this error | '''QueryException in Connection.php line 647: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'martin.applications' doesn't exist (SQL: select * from applications where applications.id in (0))'''|

0

Sign in to participate in this thread!

Eventy

Your banner here too?

KMountford kmountford Joined 17 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.