I want to fetch the files of a student with all the data.
My Tables ( I summarized the tables for what I needed. ):
students
- id
- name
student_files
- id
- student_id
- type_file_id
- file_url
type_files
- id
- name
Model:
// ...
class Student extends Authenticatable{
// ...
public function files()
{
return $this->hasMany('App\StudentFiles');
}
// ...
Controller:
// ...
class Student extends Authenticatable{
public function getFiles(Request $request)
{
$user = Student::Find($request->user()->id)->load('files');
}
// ...
I've tried something like that... does not work.
public function files()
{
return $this->hasMany('App\StudentFiles')->hasOne('App\TypeFiles');
}
The Result of request:
// ...
"files": [
{
"id": 1,
"student_id": 1,
"type_file_id": 1,
"file_url": "example.jpg",
}
]
// ...
The result that I want
// ...
"files": [
{
"id": 1,
"student_id": 1,
"type_file_id": 1,
"name": "Profile",
"file_url": "example.jpg",
}
]
// ...
I've tried it in several ways, but I can not solve my problem.
You can add the typeFile
relation to StudentFile:
class StudentFiles extends Model {
public function typeFile()
{
return $this->hasOne('App\TypeFile', 'type_file_id');
}
}
And then access it with eager load:
$user = Student::with('files', 'files.typeFile')->find($request->user()->id);
$typeFileName = $user->files->typeFile->name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.