简体   繁体   中英

Unable to get data on joining Multiple Eloquent Relationships

i wanted to display id , FileName & FilePath from Files table and id & name from User table along with the course table columns - id , courseDisplayName & aboutCourse . But it is returning null from both files & user relations.How can i fix this?

$course=Course::with(['files:id,FileName,FilePath','user:id,name'])
->select('id','courseDisplayName','aboutCourse')
->where('userId',$request->tutorId)
->get();

Course Model

  public function files()
    {
        return $this->belongsTo(Files::class, 'fileId', 'id');
    }

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

This gives an output as below:

[
    {
        "id": 20,
        "courseDisplayName": "asasasb",
        "aboutCourse": null,
        "files": null,
        "user": null
    },
    {
        "id": 14,
        "courseDisplayName": "yuu",
        "aboutCourse": "kljkl",
        "files": null,
        "user": null
    }
]

You will have to select the foreign keys fileId and userId too in order to use the relationship of files and user so the query will be like

$course=Course::with(['files:id,FileName,FilePath','user:id,name'])
->select('id','courseDisplayName','aboutCourse', 'userId', 'fileId')
->where('userId',$request->tutorId)
->get();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM