0
votes

I'm struggling with a One to Many relationship and Eloquent. I have Events (As in show events), and I have Locations. Each Event is tied to one location, but each Location might be used to host many Events. (One)Location-to-(Many)Events.

Here are my models:

class Iaevent extends Eloquent {
  public static $timestamps = true;
  public function locations() {
    return $this->has_one('Location');
  }
}

class Location extends Eloquent {
  public static $timestamps = true;
  public function iaevents() {
    return $this->has_many('Iaevent');
  }
}

If I try and echo out:

echo $iaevent->locations()->first()->company;
//or
Iaevent::find(1)->locations()->first()->company;

I get the error:

Unknown column 'iaevent_id' in 'where clause'
SQL: SELECT * FROM `locations` WHERE `iaevent_id` = ? LIMIT 1

Now... 'iaevent_id' isn't in the locations table. Rather I put 'location_id' in the 'ievents' table because one location can apply to many events, but NEVER the other way around. What have I done wrong here?

On the Laravel forum, someone suggested replacing 'has_one' with 'belongs_to' in my Iaevent model. When I do this I get an error Trying to get property of non-object

Testing the relationship the other way, with echo Location::find(1)->iaevents()->first()->name; works fine.

3

3 Answers

1
votes

The event belongs to the location.

public function location()
{
    return $this->belongs_to( 'Location' );
}

$location = $event->location()->first();

if ( $location )
    $location->name;

The 'has one' relationship is used for one to one relationships. Say events has a location_id but you only want this to be a one to one instead of a one to many. In that case the location has one event and the event belongs to a location.

0
votes

Has one works properly as it only returns one foreign element, but has_many function returns an array, so you have to index it like an array, the correct way to use it would be

Iaevent::find(1)->locations[0]->company;

0
votes

I had to specify the "foreign table" key, for example:

return $this->has_one('Location', 'id');