Support the ongoing development of →
posted 9 years ago
Last updated 1 year ago.

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 (read about the pivot table)

Last updated 1 year ago.

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 1 year ago.

It should look something like this.

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

$a_house_locations = $a_house->locations;
Last updated 1 year ago.

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 1 year ago.

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

// 2nd case - normalized
Last updated 1 year ago.

Sign in to participate in this thread!


Your banner here too?

ufeg02 ufeg02 Joined 25 Jul 2014


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

Your logo here?

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

© 2024 - All rights reserved.