【问题标题】:Create a Eloquent relationship between a parent table and a lookup table?在父表和查找表之间创建 Eloquent 关系?
【发布时间】: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_sitesmissions 的查找表,每个任务都有一个发射场(保证)。

我尝试在 Eloquent ORM 中使用 hasOnebelongsTo 关系来表示:

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_sites where launch_sites.mission_id = 3 限制 1)

我需要在 Eloquent 中设置什么关系,这样我才能正确地从这样的任务中查询和获取启动站点?

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

【问题讨论】:

    标签: php mysql database laravel orm


    【解决方案1】:

    翻转你的关系。 Mission 属于 LaunchSite 而不是相反。

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

    顺便说一下,您不需要指定LaunchSite 的表名。 launch_sites 遵守约定。

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2021-09-02
      • 1970-01-01
      • 2022-01-23
      • 2019-01-03
      相关资源
      最近更新 更多