mercredi 3 janvier 2018

proper way to create ManyToMany relationship in laravel

I just started to work on a laravel project for my school assignment. I just have started it for about a week so my fundamental knowledge about laravel is not complete.

Today I bump into a problem with model many to many relationship in laravel. I create 2 model with migration A and B. In App\A.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class A extends Model
{
    //
    public function B(){
        return $this->belongsToMany('App\B');
    }
}

and in App\B.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class B extends Model
{
    //
    public function A(){
        return $this->belongsToMany('App\A');
    }
}

I think it should do the job. But when I use seeder to create dummy data, I got the error with is that table A_B is not created. I assume that I must create empty table A_B for 2 pivot columns which is annoying. Is there a better way, a proper way to create many to many relationship without manually create pivot table for them?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire