Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

php - naming tables in many to many relationships laravel

I concerned about auto naming tables in many-to-many Laravel relationship.

for example:

Schema::create('feature_product', function (Blueprint $table) {}

when change the table name to:

Schema::create('product_feature', function (Blueprint $table) {}

I have an error in my relationship.

What's the matter with product_feature?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Laravel's naming convention for pivot tables is snake_cased model names in alphabetical order separated by an underscore. So, if one model is Feature, and the other model is Product, the pivot table will be feature_product.

You are free to use any table name you want (such as product_feature), but you will then need to specify the name of the pivot table in the relationship. This is done using the second parameter to the belongsToMany() function.

// in Product model
public function features()
{
    return $this->belongsToMany('AppFeature', 'product_feature');
}

// in Feature model
public function products()
{
    return $this->belongsToMany('AppProduct', 'product_feature');
}

You can read more about many to many relationships in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...