laravel - 我需要帮助在 Laravel 中制作三向数据透视表并显示输出
问题描述
您好,我有一个应用程序,我需要在其中向一组用户提出一系列问题。
我有三个模态问题 | 用户 | 组 A 组有很多问题,一个用户属于多个组
这是我的模型
问题:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
public function answer()
{
return $this->hasMany('App\Answer')->latest();
}
public function userAnswer(){
return $this->hasOne('App\Answer')->where('user_id', Auth()->id())->latest()->first();
}
public function group()
{
return $this->belongsToMany(Group::class);
}
}
用户:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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');
}
public function roles()
{
return $this->belongsToMany(Role::class)->withTimesamps();
}
public function assignRole($role)
{
$this->roles()->save($role);
}
public function abilities()
{
return $this->roles->map->abilities->flatten()->pluck('name')->unique();
}
public function group()
{
return $this->belongsTo(Group::class);
}
}
团体:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
public function question()
{
return $this->hasMany('App\Question');
}
}
如何制作数据透视表以便能够将添加的问题链接到特定组?
解决方案
如何制作数据透视表以便能够将添加的问题链接到特定组?
由于您建立了多对多关系,因此您应该创建一个单独的数据透视表group_question
,其中包含字段group_id
和question_id
比在附加问题的模型中,您可以这样保存它:
$question->groups()->attach($groupId);
同样,但是detach
当您想从一个或多个组中删除问题时!在这里检查
推荐阅读
- splunk - 在 splunk 查询中结合 2 个索引的结果
- azure-ad-b2c - Azure AD B2C 字符串格式声明
- wordpress - WordPress 在菜单中发布存档链接不可添加
- sql - 存储过程中的更新
- php - 如何从单行的 mysql 数据库中显示我的照片
- r - 如何展平R中列表列表中的一个元素
- node.js - 运行时错误与 Node 和 Ruby on Rails 相关
- gitlab - Gitlab 状态 API:太长(最多 255 个字符)
- mysql - 同一列上的两个约束导致的重复外键约束
- ios - 适用于 iOS 的 Google AdMob 新 SDK 设置:SKAdNetworkItems、NSUserTrackingUsageDescription、ATTrackingManager。准则 5.1.2 - 法律 - 隐私 - 数据使用