如何由laravel创建一个枢轴表

编程入门 行业动态 更新时间:2024-10-12 03:22:08
本文介绍了如何由laravel创建一个枢轴表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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_beta

2。)在新创建的迁移中,将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创建一个枢轴表

本文发布于:2023-07-09 20:52:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1088177.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:枢轴   创建一个   laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!