【问题标题】:How to access the values of a foreign key of another table using laravel如何使用 laravel 访问另一个表的外键值
【发布时间】:2016-05-16 15:57:12
【问题描述】:

我创建了一个自定义数据透视模型,它是具有 id、section_id 和 subject_id 的 SectionSubject。我现在想访问与 section_id 相关的其他值。这是我的 Sectionsubject 模型和 section_subject 表:

SectionSubject.php

class SectionSubject extends Model
{
    protected $table = 'section_subject';

    public function students()
    {
        return $this->belongsToMany(Student::class, 'section_subject_student','section_subject_id'
            )->withTimestamps();
    }

    public function assignStudents(Student $student)
    {
        return $this->students()->save($student);
    }

}

create_section_subject.php

Schema::create('section_subject', function (Blueprint $table) {
  $table->increments('id');
  $table->integer('section_id')->unsigned();
  $table->integer('subject_id')->unsigned();
  $table->string('schedule')->unique();
  $table->string('room_no');

  $table->foreign('section_id')
     ->references('id')
     ->on('sections')
     ->onDelete('cascade');

  $table->foreign('subject_id')
     ->references('id')
     ->on('subjects')
     ->onDelete('cascade');
});

现在我想获取这些值并将其放在我的 ReservationController 上。我尝试使用一对多关系,但它似乎不起作用。

class ReservationController extends Controller
{

    public function index()
    {
        $sectionSubject = SectionSubject::find(1);

        //code here
        return view('reservation.form', compact('sectionSubject');
    }

} 

【问题讨论】:

    标签: laravel laravel-5 laravel-5.1 laravel-5.2


    【解决方案1】:

    你可以通过这样做来获取关系

    $sectionSubject = SectionSubject::with('students')->find(1);
    
    //print your variable
    echo "<pre>";
     print_r($sectionSubject->toArray());
    echo "</pre>";
    

    你会找到相关的表格数据

    【讨论】:

    • 感谢您的回复。但是,请完整阅读问题。谢谢。
    • 你能分享一下你的表结构,表示哪些属于Pivot表,以及你想访问哪些其他数据?再解释一下,这样我就可以据此更新我的答案了
    猜你喜欢
    • 2015-09-15
    • 2022-11-15
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多