Nello
Nello

Reputation: 1755

Laravel Eloquent Relationship Many to Many Naming Convention

I am creating a purchased table in my application. So I have 2 tables : User and Product. Its a many to many relationship.

I know we have to create a new table for this. The naming convention for table is plural as users and products.

How would we call this purchase table? user_product or users_products?

Also I think I would need a model for this correct? If I do need a model should the naming convention for this model be User_Product?

Upvotes: 5

Views: 4580

Answers (2)

Achraf Khouadja
Achraf Khouadja

Reputation: 6269

About the naming Convention, thats just something that will make your code more readable i think, so you can name it as you like(in case you are new and learning , my opinion is that its better to avoid being stuck in conventions at first , im still learning my self)

anyway a pivot model is not required, unless you simply need some custom behaviour

I think this would help you

class User extends Model
{
    /**
     * The products that belong to the shop.
     */
    public function products()
    {
        return $this->belongsToMany('App\Products');
    }
}

you can do this : $user->products or to query $product->users, or both.

Now, with such declaration of relationships Laravel “assumes” that pivot table name obeys the rules and is user_product. But, if it’s actually different (for example, it’s plural), you can provide it as a second parameter:

return $this->belongsToMany('App\Products', 'products_users');

If you want to know how to manage these you can find more in here

Upvotes: 1

maiorano84
maiorano84

Reputation: 11951

From the documentation:

As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method

In your case, Laravel assumes that your joining table would be named product_user. No extra model is needed:

User.php

class User extends Model
{
    //...
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
    //...
}

Product.php

class Product extends Model
{
    //...
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
    //...
}

And your schemas would look like so:

users table migration

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    //...
});

products table migration

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    //...
});

product_user table migration

Schema::create('product_user', function (Blueprint $table) {
    $table->integer('product_id');
    $table->integer('user_id');
    //...
});

Upvotes: 9

Related Questions