Miko Mi Miko Mi - 1 year ago 104
PHP Question

Laravel: How do I create the relationship and which one do I use?

I have the database structure that have a

classes
table, a
users
table and
users_classes
table that matches the other two, because a user can belong to multiple classes. I have a problem now. I have code like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Classes extends Model
{
protected $table = 'classes';

public function students()
{

}
}


And I want to be able to access the students of the class by typing
$class = Classes::find(1)
and then
$class->students
to access the students. How do I define the relationship without using the query builder? I want to use eloquent. Im a noobie in Laravel pls dont downvote.

Answer Source

You use a belongsToMany relation.

If your users_classes table has the fields user_id and class_id you can do the following:

public function students()
{
    return $this->belongsToMany(Student::class, 'users_classes', 'class_id', 'user_id');
}  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download