在Laravel 4中,当与 http:// 4 .laravel / docs / eloquent#many-to-many ,我如何才能真正让Laravel为我创建数据透视表?
In Laravel 4, when working with many-to-many relationships as described in four.laravel/docs/eloquent#many-to-many, how can I actually get Laravel to create the pivot table for me?
我需要在涉及的两个模型的迁移中添加一些内容?我需要手动创建数据透视表的迁移吗?或者Laravel如何知道创建数据透视表?
Do I need to add something in my migrations for the two models that are involved? Do I need to manually create a migration for the pivot table? Or how does Laravel know to create the pivot table?
我迄今为止所做的所有事情都是添加 belongsToMany 信息到两个各自的模型,即
All I've done so far is add the belongsToMany information to the two respective models, i.e.
class User extends Eloquent { public function roles() { return $this->belongsToMany('Role'); } }但是,这不会触发创建数据透视表?我缺少什么步骤?
However, that does not trigger creation of the pivot table? What step am I missing?
推荐答案看起来好像需要手动创建数据透视表(即Laravel不做这个自动)。以下是这样做:
It appears as though the pivot table does need to be created manually (i.e. Laravel does not do this automatically). Here's how to do it:
1)使用字母顺序顺序使用单数表名创建新的迁移(默认):
1.) Create a new migration, using singular table names in alphabetical order (default):
php artisan migrate:make create_alpha_beta_table --create --table=alpha_beta2。)在新创建的迁移中,将up函数更改为:
2.) Inside the newly created migration, change the up function to:
public function up() { Schema::create('alpha_beta', function(Blueprint $table) { $table->increments('id'); $table->integer('alpha_id'); $table->integer('beta_id'); }); }3)如果需要,添加外键约束。 (我还没有得到这个点)。
3.) Add the foreign key constraints, if desired. (I haven't gotten to that bit, yet).
现在要种下,说, alpha表,使用Beta的密钥,您可以在AlphaTableSeeder中执行以下操作:
Now to seed, say, the alpha table, using keys from beta, you can do the following in your AlphaTableSeeder:
public function run() { DB::table('alpha')->delete(); Alpha::create( array( 'all' => 'all', 'your' => 'your', 'stuff' => 'stuff', ) )->beta()->attach( $idOfYourBeta ); }更多推荐
如何由laravel创建一个枢轴表
发布评论