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

The short answer is yes, if I understand what you want to do then setting up your model with pivot tables is the way to go

http://laravel.com/docs/eloquent (read about the pivot table)

Last updated 2 years ago.
0

I don't get it I think.

I have three tables:

** Houses ** id (auto increment) propcode (unique codes as used in my country)

** Location ** id (auto increment) locationcode (unique code)

** HouseLocations ** id propcode locationcode

In my model House I have the following:

public function locations() {
	return $this->belongsToMany('Location', 'tblhouselocations', 'propcode', 'locationcode');
}

I use belongsToMany because a house got multiple locations in my pivot table tblhouselocations.

When I do a var_dump on House there is no locations returned. The array is empty. What am I doing wrong?

Last updated 2 years ago.
0

It should look something like this.

$a_house = $House::where('name', '=', '123');

$a_house_locations = $a_house->locations;
Last updated 2 years ago.
0

Is it possible that the pivot-table is not working because I do not refer to the ID-fields in the table houses and locations?

Last updated 2 years ago.
0

No, as long as primaryKey on the model is set (or it's default id field). If you get empty array, then it means that the relation works, but there are no rows returned for given house.

To answer your original question: yes, of course it is possible to get all the related rows.

I suggest you either:

1 create 3 models: City, Region, Country with global scopes (if you have 2 foreign keys, 1 for region, 1 for country). OR 2 normalize that thing and create separate tables for the above models.

Then you need to setup relations accordingly (depending on which way you choose) and then you can load everything like this:

$house = House::first();

// 1st case
$house->city;
$house->region;
$house->country;

// 2nd case - normalized
$house->city->region->country;
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

ufeg02 ufeg02 Joined 25 Jul 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.