0
votes

I'm wondering how, but it's bit confusing.

I have fine belongs to many relation between users and groups tables as well as appropriate models for all of that.

But i also have table students, where not all users are student so i students table i maintain user_id field.

My question would be: Can i use pivot table "group_user" for relations between student and group model, in students table i have "user_id" field? and how?

I tried something like

public function students()
{
return $this->belongsToMany('Student','group_user','group_id','user_id');
{

but i don't see the way how to tell eloquent not to take students.id but to take students.user_id???

1
No, you can't do that easily. You would need to override a few methods on BelongsToMany and on your Models, so I wouldn't do that. It's not worth the effort. - Jarek Tkaczyk
what else could help? how can i easily just fetch those users? any idea? - user2260237
You asked if you could use the pivot table, so I don't know which users you want. Rephrase your question and say, what you need exactly. - Jarek Tkaczyk
I have 4 tables "students" ---> "users" "subjects" -> "groups" And there is pivot table between groups and users "group_user" "students" table just extend some more data for users that are student and same thing with "subjects" table, it extends some data for "groups" since not all groups are "subjects" No i want to list all users belonging to certain subject and related data for them, name(which is in "users" table), student_id(which is in "students" table) and subject's name - user2260237

1 Answers

0
votes

Assuming these relations:

Subject belongsTo Group
Group belongsToMany User
User hasOne Student

you can easily do this:

$subject = Subject::find($someId);
// of course for multiple subject use eager loading:
// $subjects = Subject::with('group.users.student')->get();

$users = $subject->group->users; // related users

foreach ($users as $user)
{
  $user->student; // null|student model
}