【发布时间】:2020-12-04 03:27:55
【问题描述】:
我有一个项目,其中有 3 个表,一个问题表,一个答案表和一个用户表
在问题表中,我有以下内容:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->timestamps();
});
在用户表中,我有以下内容:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('district')->nullable();
$table->string('area')->nullable();
$table->string('committee')->nullable();
$table->string('position')->nullable();
$table->rememberToken();
$table->timestamps();
});
在答案表中,我有以下内容:
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('question_id');
$table->foreign('question_id')->references('id')->on('questions');
$table->string('answer');
$table->timestamps();
});
这些是模型
class Answer extends Model
{
public function user(){
return $this->hasOne('App\User');
}
public function question(){
return $this->hasOne('App\Question');
}
}
class Question extends Model
{
public function answer(){
return $this->hasMany('App\Answer');
}
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','district','area','committee','position',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function answer(){
return $this->hasMany('App\Answer');
}
}
根据我的结构,答案表将包含由 user_id 和他对一个问题的回答组成的每一行的条目,在下一行中是另一个问题
如何检索表格中的数据,该表格在第一行显示用户在一列中,他的所有 4 个答案在以下 4 列中?
【问题讨论】:
-
你的关系在模型中定义了吗?>
-
是的,我会编辑我的问题