Can't get data from table using function belongsToMany

Narek :

I'm trying to store students data in array with groups data. For example:

groups

id - 1
name - P1
student_id - 1

id - 2
name - P1
student_id - 2

id - 3
name - P2
student_id - 3

Here I want gate data like this

[
  {name: 'P1', students: [{id: 1, name: 'John'}, {id: 2, name: 'Liza'}]},
  {name: 'P2', students: [{id: 3, name: 'Bob'}]},
]

Tables:

users

id - bigint unsigned
name - string
...other columns

groups

id - bigint unsigned
name - string
student_id
...other columns

Group.php model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Groups extends Model
{
    public $table = "groups";
    public $timestamps = false;

    public function students(){
        return $this->belongsToMany('App\User', 'groups', 'student_id', 'id');
    }
}

UserController.php

public function groupsAdmin(){
   return view("groups", ["groups" => Groups::with(['students'])->get()]);
}

With this code I'm getting empty students array.

Eissaweb :

its, belongsToMany from users to groups so it should be like this.

you need another table(pivot table), name it group_user.

group_user table:-
user_id
group_id

and completely remove the student_id from grups table.

now go to User model and put this method:

public function groups()
{
    return $this->belongsToMany(Group::class);
}

and go to Group Model and put this code

 public function users()
 {
    return $this->belongsToMany(User::class);
 }

with this code above, you can access groups from user and users from a group, like so:

$user = User::first();
$groups = $user->groups;

Hope this helps, see the Doc here: Eloquent Many to Many relationship

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=293275&siteId=1