php - 如何在 Laravel 中向数据透视表添加记录

标签 php laravel eloquent

我有一个用户、学生和学科模型,我想将学生注册到多个学科。因此,我创建了一个 StudentRegistration Controller ,并在创建 View 中显示属于当前登录用户的类(class)的所有主题。

StudentRegistration.php创建函数

public function create()
{
    $user_id = Auth::user()->id;
    $student_id = Student::where('user_id', $user_id)->first();
    $course = $student_id->course->id;
    $subjects = Subject::where('course_id', $course)->get();

    return view('student.create', compact('subjects'));

}

在创建模板中,我将所有主题显示为复选框,因为用户可以注册多个主题。

{!! Form::open(['method' => 'POST', 'action'=>'StudentRegistration@store', 'files'=>true]) !!}
    @foreach($subjects as $subject)
    <div class="label-box">
        {!! Form::label('name', $subject->name) !!}
        {!! Form::checkbox('subject_id[]', $subject->id, null, ['class'=>'form-control']) !!}
    </div>
    @endforeach
    <div class="form-group">
        {!! Form::submit('Create User', ['class'=>'btn btn-primary']) !!}
    </div>      
{!! Form::close() !!}

我在 Student.php 中有这个用于多对多关系:

public function subjects()
{
    return $this->belongsToMany('App\Subject');
}

我创建了一个名为 Student_Subject 的数据透视表。那么,在存储期间,如何将所有选定的主题保存到数据透视表(student_subject)中。

我尝试使用这个:

public function store(Request $request)
{
    $data = $request->except('_token');
    $subject_count = count($data['subject_id']);
    for($i=0; $i < $subject_count; $i++){
       $student = Student::where('user_id', Auth::user()->id);
       $student->subjects()->attach($data['subject_id'][$i]);
    }
}

但我收到以下错误:

"Method Illuminate\Database\Query\Builder::subjects does not exist."

如何查看学生未注册的所有类(class)科目?

我有这个:

Route::get('/studentsubjects', function(){
    $student_id = Student::where('user_id', Auth::id())->first();
    $course = $student_id->course->id;
    $subjects = $student_id->subjects;

    echo 'Registered at' .'<br>';
    foreach ($subjects as $registered) {
        echo $registered->name .'<br>';
    }

    $unregistered = Subject::where('course_id', $course)->except($subjects);
});

并看到此错误:

"Method Illuminate\Database\Query\Builder::except does not exist."

最佳答案

$student = Student::where('user_id', Auth::user()->id);

不足以获取 Student 模型,您仅在此处获取查询对象。

为了真正获得学生,请使用以下内容:

$student = Student::where('user_id', Auth::user()->id)->first();

如果 user_id 是模型 Student 的主键,那就更好了:

$student = Student::find(Auth::user()->id);

顺便说一句,您可以使用 Auth::id() 而不是 Auth::user( )->id,结果是:

$student = Student::find(Auth::id());

关于php - 如何在 Laravel 中向数据透视表添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50694213/

相关文章:

php - 根据先前在 PHP 中查询的结果从 MySQL 中选择数据

拉维尔 5.2 : withErrors on redirect not working

mysql - Laravel MySQL 仅在计划任务上出错(通过 cron)

php - Laravel Eloquent Relationship 按关系列过滤

php - 我如何对数据库中的值进行计数和求和

php - 多行单引号字符串

php - laravel 5.4 分页 links() 方法返回空 html

laravel - 将参数传递给 laravel Eloquent api 资源构造函数

php - 将整个 Slim 应用程序打包到 Phar 文件中时出错

laravel - 在工匠修补匠中调用模型类的别名