【发布时间】:2015-03-19 20:02:37
【问题描述】:
我正在使用 Laravel 4.2,我正在慢慢构建一个复杂的网站,我遇到了两个表之间的关系,我无法立即弄清楚如何与 Eloquent 一起映射。以下是相关架构:
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>
如您所见,表launch_sites 是missions 的查找表,每个任务都有一个发射场(保证)。
我尝试在 Eloquent ORM 中使用 hasOne 和 belongsTo 关系来表示:
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');
}
}
但是,我很快意识到这行不通,因为发射场不“属于”任务。有了这种关系,我得到了错误:
找不到列:1054 'where 子句'中的未知列'launch_sites.mission_id'(SQL:select * from
launch_siteswherelaunch_sites.mission_id= 3 限制 1)
我需要在 Eloquent 中设置什么关系,这样我才能正确地从这样的任务中查询和获取启动站点?
Mission::{{Some Query}}->with('launchSite');
【问题讨论】:
标签: php mysql database laravel orm