gpt4 book ai didi

mysql - Laravel 如何通过在模型中传递属性来显示行

转载 作者:行者123 更新时间:2023-11-29 20:16:17 27 4
gpt4 key购买 nike

我试图根据学生表中名为“stn”的属性为我的学生显示对象。当我使用主键时,我能够显示它,但是当使用属性时,该函数不返回任何内容,而当它用于返回对象时。

@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);
}

}

最佳答案

在你的 Controller 中你必须有这样的东西:

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'));
}

与您的 View 相同

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

关于mysql - Laravel 如何通过在模型中传递属性来显示行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com