简体   繁体   中英

Laravel relationships setup

I'm working on a Laravel installation where I have (among other things)

  • Teachers (table:users (cols: id, name, type), model:User, users.type = 2)
  • Students (table:users (id, name, type), model:User, users.type = 1)
  • Schools (table:schools (id, name), model:School)
  • Collections of students (table:student_collection (id, name), model:StudentCollection)
  • & table student_collections_users for linking the student-users to collections (model: StudentsCollections, columns id, user_id, collection_id)

I have managed to setup some relationships, but can't get my head around to get

  • Which teachers teach a student
  • Which collections does a student belong to

Currently I'm trying to get the collections with

//User.php
public function collections() {
    $collection = $this->hasManyThrough('\App\StudentsCollections', '\App\User', 'id', 'user_id');
    return $collection;
}

//Controller
$user = \App\User::find($id);
$user->collections = $user->collections();

but it only returns the id's of the collections. How can I get the full data object for each collection?

I'm using Laravel 5.3.

First, In your example code, are the table names correct?

I see a table called 'students_collections', but your belongsToMany has a table name (second param) 'student_collections_users'. That's a typo, I presume.

Second, what does return an empty result? Calling the collections method or the collections property on the User model? Can you add some sample code?

Third: you have actual data in the database (through a seeder or real data)? I know this is obvious, but sometimes people tend to forget the obvious... :-)

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