Laravel从数据透视表多对多关系中获取数据

Laravel从数据透视表多对多关系中获取数据,laravel,eloquent,relationship,Laravel,Eloquent,Relationship,我想得到具体笔记的课程。这里,注释id和类id位于透视表中 Note.php public function classes() { return $this->belongsToMany(MyClass::class); } MyClass.php public function notes() { return $this->belongsToMany(Note::class);

我想得到具体笔记的课程。这里,注释id和类id位于透视表中

Note.php

    public function classes()
        {
            return $this->belongsToMany(MyClass::class);
        }

MyClass.php

public function notes()
    {
        return $this->belongsToMany(Note::class);
    }
我正在通过成功保存数据

$note->classes()->attach($request->class);
MyClass迁移

Schema::create('my_classes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });
Schema::create('notes', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('image')->nullable();

            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });
Notes迁移

Schema::create('my_classes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });
Schema::create('notes', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('image')->nullable();

            $table->timestamps();

            $table->boolean('isDeleted')->default(false);
            $table->dateTime('deletedAt')->nullable();
        });
我的课堂笔记迁移

Schema::create('my_class_note', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->foreignId('my_class_id')->constrained();
            $table->foreignId('note_id')->constrained();

            $table->timestamps();
        });

需要帮助获取特定笔记的课程。一个注释可以有许多类。

您只需使用relationship属性访问它,如果您定义了一个关系,则总会有

// returns a collection of classes
$classes = Note::find(1)->classes;
在你的控制器里

return view('yourview', ['classes' => $classes]);
在你看来

@foreach($classes as $class)
    <p>{{$class->name}}</p>
@endforeach

您可以使用relationship属性简单地访问它,如果您已经定义了关系,则始终会有

// returns a collection of classes
$classes = Note::find(1)->classes;
在你的控制器里

return view('yourview', ['classes' => $classes]);
在你看来

@foreach($classes as $class)
    <p>{{$class->name}}</p>
@endforeach

你的问题似乎有点直截了当,如果我误解了,请告诉我:非常感谢。使用foreach$note->classes作为$class{!!$class->name!!}endforeach进入刀片文件如果它解决了问题,请记住接受它作为答案:您的问题似乎有点直截了当,如果我误解了,请告诉我:非常感谢。使用foreach$note->classes作为$class{!!$class->name!!}endforeach进入刀片文件如果它解决了问题,请记住接受它作为答案: