【问题标题】:Laravel get data from pivot table many to many relationshipLaravel 从数据透视表中获取多对多关系数据
【发布时间】:2020-12-23 08:56:52
【问题描述】:

Tables with relationship

我想获取特定笔记的课程。这里注意 id 和 class 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();
        });

my_class_note 迁移

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

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

            $table->timestamps();
        });

在获取特定笔记的课程方面需要帮助。一个笔记可以有多个类。

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    您可以使用关系属性简单地访问它,如果您定义了关系,总会有。

    // 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-&gt;classes as $class) {!! $class-&gt;name !!} endforeach进入刀片文件
    • 如果它解决了问题,请记住接受它作为答案:)
    猜你喜欢
    • 2020-07-03
    • 2018-09-15
    • 1970-01-01
    • 2015-02-10
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    相关资源
    最近更新 更多