Laravel数据透视表和间接关系 [英] Laravel Pivot Table and indirect relationship

查看:109
本文介绍了Laravel数据透视表和间接关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Laravel 4进行调查,需要用户多次进行相同的调查(并将答案保存为不同的实例)。


$ b $我目前有一个名为survey_user的数据透视表,用于将用户链接到受邀的调查。数据透视表的一个潜在的积极的副作用是它的主键可以被用来进行唯一的调查实例。



我的问题是找出如何获得答案,具体来说用户模型。答案表将包含数据透视表主要的外键。



我的用户模型:

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

public function answers(){
//这应该返回所有用户的答案,而不管
//调查ID。
}
}

表:

 调查:id 
用户:id
survey_user:id,survey_id,user_id,completed_at
答案:survey_user_id,answer_text,..

我如何完成这个伪装关系或者更好的结构方式?

解决方案

使用关系!以下是我将如何做:

  class User Enloquent {
public function investigation(){
return $ this-> belongsToMany('Survey');
}

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

类调查延伸口述{
public function investigation(){
return $ this-> belongsToMany('User');
}

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

class答案扩展Eloquent {
public function survey(){
return $ this-> belongsTo('Survey');
}

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


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?

解决方案

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');
    }
}

这篇关于Laravel数据透视表和间接关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆