首页 > 解决方案 > 我需要帮助在 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');
  }
}

如何制作数据透视表以便能够将添加的问题链接到特定组?

标签: laraveleloquent

解决方案


如何制作数据透视表以便能够将添加的问题链接到特定组?

由于您建立了多对多关系,因此您应该创建一个单独的数据透视表group_question,其中包含字段group_idquestion_id

比在附加问题的模型中,您可以这样保存它:

$question->groups()->attach($groupId);

同样,但是detach当您想从一个或多个组中删除问题时!在这里检查


推荐阅读