Laravel Pivot Table and indirect relationship

痴心易碎 提交于 2019-12-11 14:57:53

问题


I'm writing a survey with Laravel 4 and need the ability for users to be able to take the same survey multiple times (and have their answers saved as different instances.)

I currently have a pivot table called survey_user that links a user to an invited survey. A potentially positive side effect of the pivot table is that its primary key could be used to have unique survey instances.

My problem is figuring out how to get answers, specifically through the user model. Answers table would contain a foreign key to the primary of the pivot table.

My User model:

class User extends Eloquent {
  public function surveys() {
    return $this->belongsToMany('Survey', 'survey_user')
                ->withPivot('id', 'completed_at');
  }

  public function answers() {
     // This should return all of the user's answers, irrespective of 
     // survey id's.
  }
}

Tables:

surveys: id
users: id
survey_user: id, survey_id, user_id, completed_at
answers: survey_user_id, answer_text, ...

How might I accomplish this psuedo-relationship or perhaps a better way to structure?


回答1:


Use relationships! Here's how I would do it:

class User extends Eloquent {
    public function surveys() {
        return $this->belongsToMany('Survey');
    }

    public function answers() {
        return $this->hasMany('Answer');
    }
}

class Survey extends Eloquent {
    public function surveys() {
        return $this->belongsToMany('User');
    }

    public function answers() {
        return $this->hasMany('Answer');
    }
}

class Answer extends Eloquent {
    public function survey() {
        return $this->belongsTo('Survey');
    }

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


来源:https://stackoverflow.com/questions/19805567/laravel-pivot-table-and-indirect-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!