Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

Have you set up a working relationship between the 4 tables?

If so you should be able to do something like this,

$user = User::find(1)->get();
//Using Eager Loading
$user->load('country');
//then access the country fields from the user like so
$user->country->name

If not, i can help you set up one.

Last updated 2 years ago.
0

Hi evandertino, thanks for your message; relationships works 100%.

Laravel documentation is poor about Eager Loading (http://laravel.com/docs/eloquent#eager-loading) =(

After many tries I found out a soluction:

$results = User::with([
	'country' => function ($query) {
		$query->select('id','name');
	},'posts' => function ($query) {
		$query->select('id','user_id','title');
	},'posts.attachments' => function ($query) {
		$query->select('id','post_id','type');
	}])->get(['id','country_id','name']); 

Yo need to add either the primary key or the foreign key to the field list.

Last updated 2 years ago.
0

Your code will work for this kind of relation but you need to select also all foreign keys to let Eloquent match related models to their parents.

Last updated 2 years ago.
0

Ah, okay i note that

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

luismec90 luismec90 Joined 29 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.