【问题标题】:Filter out unselected fields from table via Many to Many relationship in Laravel通过 Laravel 中的多对多关系从表中过滤掉未选择的字段
【发布时间】:2020-11-03 10:46:13
【问题描述】:

在我的项目中,用户在注册时只能选择一项考试。但登录网站后,用户可以添加另一个考试。现在的问题是,如果用户在注册时选择了一项特定的考试,他就不能再次添加相同的考试。换句话说,我只想向该用户显示他/她未添加的未选择考试。因为我在用户模型中实现了多对多关系。

1) 用户.php

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $primaryKey = 'uid';

    public function exams()
    {
        return $this->belongsToMany(exam::class, 'exam_user', 'user_id', 'exam_id')->withTimeStamps();
    }
}

2) UsersController.php

class UsersController extends Controller
{
    
    public function __construct()
    {
        $this->middleware(['auth','verified']);
    }

    public function fetchExams()
    {
        $users = Auth::user();
        $exams_model = exam::all();
        return view('user.myExam', compact('users', 'exams_model'));
    }
}

3) myExam.blade.php

  • 在此视图中,用户可以看到他/她在一张表中选择了哪个考试,但我想要 向用户显示该用户未特别选择的考试。
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <h2>Your Exams</h2>
            @foreach ($users->exams as $exam)
                <p><kbd style="background-color: green; font-size: 16px;">{{$exam->exam_name}}</kbd></p>
            @endforeach
        </div>
        <div class="col-md-6">
            <form action="/addExam" method="POST">
                @csrf
                <h2>Add new exam</h2>
                @foreach ($exams_model as $ex)
                    <p><input type="checkbox" name="{{$ex->eid}}"> <kbd style="background-color: lightblue; color: black; font-size: 16px;">{{$ex->exam_name}}</kbd></p>
                @endforeach
            </form>
        </div>
    </div>
</div>
@endsection

4) 用户表

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('uid');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('phone')->unique();
            $table->boolean('status')->default(0);
            $table->string('password');
            $table->string('profile_image')->default('default.jpg');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

5) 考试表

class CreateExamsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('exams', function (Blueprint $table) {
            $table->increments('eid');
            $table->string('exam_name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('exams');
    }
}

6)exam_user 表

  • 此表将 user_id 和exam_id 存储为外键。
class CreateUserExamsPivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('exam_user', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('exam_id');
            $table->foreign('exam_id')->references('eid')->on('exams');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('uid')->on('users');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('exam_user');
    }
}

【问题讨论】:

    标签: php mysql laravel eloquent laravel-7


    【解决方案1】:

    据我了解,您只需要显示来自exams 的内容,而不是对exam_useruser_id!=(Logged in user) 的表的引用

    简单的 SQL 查询可能是这样的

    select distinct e.* from exams as e join exam_user as eu on eu.exam_id = e.eid where eu.user_id = Auth::user()-&gt;uid;

    Laravel 的非雄辩方式

    $exams = DB::table('exams as e')-&gt;left join('exam_user as eu','eu.exam_id','e.eid')-&gt;where('eu.user_id','!=',Auth::user()-&gt;uid)-&gt;get();

    雄辩之道

    You can get from above non eloquent way. I'm not sure. But above code will work (not tested)

    【讨论】:

    • 它只显示其他用户的考试。前任。 - 如果 John 参加了名为 UPSC 的考试,而 Mark 参加了名为 GATE 的考试。从您的代码中,John 只能添加 Mark 选择的 GATE 考试,Mark 只能添加 John 选择的 UPSC 考试。但问题是 John 可以添加除 UPSC 之外的任何考试,而 Mark 可以添加除 GATE 之外的任何考试。
    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2023-03-06
    • 2020-07-15
    • 2013-12-03
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多