mysql - Laravel Eloquent 试图检索表中具有相同外键的所有答案
问题描述
我有一个项目,其中有 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 列中?
解决方案
第一个Answer
模型应该是这样的。因为它是一对多的。
class Answer extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function question(){
return $this->belongsTo('App\Question');
}
}
然后你可以得到这样的数据:
$results = User::with('answer')->first();
// this should give the first `user` with all the answers that belongs to the user.
$results = User::with('answer')->get();
// this should give you all the users.
假设您需要所有用户和所有答案。
foreach ($results as $user) {
echo $user->name;
foreach ($user->answer as $value) {
echo $value->answer;
}
}
让我知道它是否有帮助。
推荐阅读
- android - 如何制作 2(双)环自定义进度条
- scala - DataFrame 有 50 个分区,没有调用 repartitions() 方法,调用 repartitions() 方法后基于列创建分区
- sql - 在一行中显示表 DATA
- go - 当用户已被确认时,Cognito 抛出 ErrCodeNotAuthorizedException
- java - 如何使用 JOOQ 从模板和参数占位符生成 sql?
- php - Apache mod_rewrite 返回文件为 404 而不是 200
- r - 在R中将(半)长格式更改为宽格式
- peoplesoft - Peoplesoft - 使用自定义取消按钮终止 appengine
- css - 如何在盒子底部显示这种阴影 - 三角形深度阴影
- javascript - 有没有办法将插入的值例如 1234567890 拆分为 12345 和 67890?