marked-down
marked-down

Reputation: 10408

Create a Eloquent relationship between a parent table and a lookup table?

I'm using Laravel 4.2 and I'm slowly building a complex website, and I've come across a relationship between two of my tables that I cannot immediately figure out how to map together with Eloquent. Here is the relevant schema:

table `missions`
mission_id (PK) | name           | launch_site_id (FK)
------------------------------------------------------
1              | someMission    | 1
2              | anotherMission | 3
3              | moreMissions   | 1

table `launch_sites`
launch_site_id (PK) | name   | location
------------------------------------------------------
1                  | Kwaj    | <some coordinate>
2                  | Florida | <some coordinate>
3                  | Russia  | <some coordinate>

As you can see, the table launch_sites is a lookup table for missions, and each mission has a single launch site (guaranteed).

I tried representing this with a hasOne & belongsTo relationship in Eloquent ORM:

class Mission extends Eloquent {
    public function launchSite() {
        return $this->hasOne('LaunchSite');
    }
}

class LaunchSite extends Eloquent {
    protected $table = 'launch_sites';

    public function mission() {
        return $this->belongsTo('mission');
    }
}

However, I quickly realized this would not work as a launch site does not "belong to" a mission. With this relationship, I get the error:

Column not found: 1054 Unknown column 'launch_sites.mission_id' in 'where clause' (SQL: select * from launch_sites where launch_sites.mission_id = 3 limit 1)

What relationship setup in Eloquent do I want so I can correctly query and fetch the launch site from a mission like so?

Mission::{{Some Query}}->with('launchSite'); 

Upvotes: 0

Views: 116

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152890

Flip your relationships around. Mission belongs to LaunchSite not the other way around.

class Mission extends Eloquent {
    public function launchSite() {
        return $this->belongsTo('LaunchSite');
    }
}

class LaunchSite extends Eloquent {
    public function mission() {
        return $this->hasOne('mission');
    }
}

By the way you shouldn't need to specify the table name of LaunchSite. launch_sites is following the convention.

Upvotes: 1

Related Questions