2016-09-29 34 views
0

我試圖根據學生表中名爲「stn」的屬性顯示我的學生的對象。當我使用主鍵時,我可以顯示它,但是當使用一個屬性時,函數返回一個對象時什麼都不返回。Laravel如何通過在我的模型中傳遞屬性來顯示行

@foreach($users as $user) 

    @foreach($user->contactlogs as $logs) 

     {{ $logs->students }} 

    @endforeach 

@endforeach 

這用來顯示學生對象,現在它來了什麼也沒有,這是我的模型

class ContactLog extends Model 
{ 

    protected $table = 'contactlogs'; 

    public function users() 
    { 
     return $this->belongsTo(User::class, 'id'); 
    } 
    public function students() 
    { 
     return $this->belongsTo(Student::Class); 
    } 

} 

class Student extends Model 
{ 

    protected $table = 'students'; 

    public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

    public function contactlogs() 
    { 
     return $this->hasMany(ContactLog::class); 
    } 

} 

回答

0

我能夠顯示的信息通過以下方式

$student = Student::where('stn', '=', $request->stn)->first(); 

    $log->student_id = $student->id; 

它在哪裏運行一個se arch爲stn並取回第一場比賽,這些都是獨特的,所以它應該工作,然後它存儲ID,並在視圖中,我可以只顯示STN而不是ID

0

那麼在你的控制器,你必須有這樣的事情:

public function yourAction(){ 
    $users = ContactLog::with('users', 'students')->get(); 
    return view('your.view' , compact('users')); 
} 

然後在您看來,您必須做到這一點:

@foreach($users as $user) 
{{ $user->users->name }} 
{{ $user->students->name }} 
@endforeach 

而且你可以爲學生做同樣太:對你的看法

public function yourAction(){ 
    $students = Student::with('users', 'contactlogs')->get(); 
     return view('your.view' , compact('students')); 
} 

相同

@foreach($students as $student) 
    {{ $student->users->attr }} //attr is the attribute from users 
    {{ $student->contactlogs->attr }}// attr is the attribute from contaclogs 
@endforeach 
+0

感謝您抽出寶貴的時間來幫幫忙,我不勝感激! – gxrobb

0

嘗試contactlogs() contactlogs

@foreach($用戶爲$用戶)

@foreach($user->contactlogs() as $logs) 

    {{ $logs->students }} 

@endforeach 

@endforeach

相關問題