سؤال

I have a User class with the following:

public function school()
{
    return $this->belongsToMany('School');
}

I have a School class with the following:

public function user()
{
    return $this->belongsToMany('User');
}

I create my pivot table use the pivot generator, here is the migrate for it:

public function up()
{
    Schema::create('school_user', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('school_id')->unsigned()->index();
        $table->foreign('school_id')->references('id')->on('schools')->onDelete('cascade');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->boolean('admin');
        $table->timestamps();
    });
}

There is only one item in the user table, the school table, and the pivot table. When I do

$user = User::where('email', '=', Input::get('email'))->first();
$schools = $user->schools;
return Response::json([
    'success' => true, 
    'user' => $user->toArray(),
    'schools' => $schools
]);

It returns a null for the schools. Am I missing something?

هل كانت مفيدة؟

المحلول

You have declared:

public function school()
{
    return $this->belongsToMany('School');
}

But using $user->schools, you should change the function declaration to schools:

public function schools()
{
    //...
}

Also make sure that, you are using the right relationship, I'm confussed because one user may belongs to only one school (logically).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top