簡體   English   中英

Laravel雄辯的一對多關系數據未顯示

[英]Laravel eloquent one to many relationship data not showing

我有兩個表, 學生表具有列(id,family_id,名稱,類,節) 家庭表具有列(family_id,mobile_no,professional)

-我創建了兩個模型。 學生模型:

class student extends Model
{

}

家庭模式

class family extends Model
{
  public function student()
    {
        return $this->hasMany('App\student');

    }
}

-我能夠顯示學生表中的所有數據,我的控制器是:

public function index()
    {
       $finddata = student::orderBy('id', 'asc')->get();
      return view('students.index')->with('finddata', $finddata); }

- 在家庭模式中嘗試過的方法

返回$ this-> hasMany('App \\ students');

我想要的是;

  • 我想將家庭模式與學生模式聯系起來。
  • 索引頁面將僅包含所有學生的姓名。 我已經做了
  • 當我單擊學生姓名時,它應該顯示,有關特定學生的所有信息以及他的家庭信息。 現在,它僅顯示來自學生表的信息。

你應該試試這個

class student extends Model
{

    public function familyId(){
        return $this->belongsTo(Family::class,'family_id');
    }

}

當您單擊學生姓名時,它將重定向到學生/ {id}

路線

路線:: get('student / {id}','StudentController @ show');

學生負責人

public function show(Request $request, $id)
{
    $student = student::find($id);
    return view('student.show')->with('student', $student); 
}

student.show.blade文件

Mobile no: {{ $student->familyId->mobile_no }}
Profession: {{ $student->familyId->profession }}

在學生模型中:

class student extends Model
{
    public function family(){
        return $this->belongsTo(Family::class,'family_id');
    }

}

然后,您可以通過以下方式訪問Blade中的家庭信息:

{{$student->family->mobile_no}}
{{$student->family->profession}}

您最好使用artisan命令來生成模型和控制器,以便獲得遵循命名約定(例如大寫Class名稱)的自動模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM