【问题标题】:Laravel 8 : How to create a Pivot Model with its associated migration?Laravel 8:如何创建具有相关迁移的 Pivot 模型?
【发布时间】:2022-01-15 23:15:54
【问题描述】:

我想创建一个模型:FormsUser 和迁移:forms_user

因为我在创建表单时遇到问题,所以将表用作数据透视表我被告知该表:'forms_users 不存在',因为我单独创建了迁移并且 当我转到我的组成员管理页面时,我收到错误:'forms_users 不存在',因为在这里我必须使用数据透视表,所以它必须有这个表名......

您能帮我解决这个问题或提出替代方案吗? 简而言之,我想创建一个表单并创建一个团队,我可以在其中将其他用户添加到相同的表单中。

迁移:表格和模型表格:

class Forms extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'title',
        'description',
        'date',
        'color',
        'progress',
        'user_id',
        'groupe_id',
        'formulaire',
        'logo',
    ];

    protected $dates = [
        'created_at',
        'deleted_at',
        'started_at',
        'update_at'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function usersGroupe()
    {
        return $this->belongsToMany(User::class);
    }
}

迁移:用户和模型用户:

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'lastname',
        'firstname',
        'email',
        'password',
        'current_team_id',
        'profile_photo_path',
        'role_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
        'role_id',
    ];

    protected $dates = [
        'created_at',
        'deleted_at',
        'started_at',
        'update_at'
    ];

    public function forms()
    {
        return $this->hasMany(Forms::class);
    }

    public function formGroupe()
    {
        return $this->belongsToMany(Forms::class);
    }

    public function role()
    {
        //return $this->hasMany(Role::class, 'id', 'role_id');
        return $this->hasOne(Role::class, 'id', 'role_id');
    }

    public function user()
    {
        return $this->hasOne(User::class);
    }
}

迁移:formuser && 模型 FormsUser :

class FormsUser extends Model
{
    use HasFactory;

    protected $fillable = [
        'forms_id',
        'user_id'
    ];
}

迁移 create_forms_user :

Schema::create('forms_user', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('forms_id');
            $table->foreign('forms_id')->references('id')->on('forms');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
        });

【问题讨论】:

标签: laravel migration pivot-table laravel-8 laravel-models


【解决方案1】:

因此,传统上您不必创建枢轴模型。 Laravel 有一些命名约定,如果你坚持下去,事情会变得更容易一些。例如,模型应该是单数,但表名应该是复数,除了数据透视表。例如,您的模型应如下所示:

class User extends Model { ... }

class Form extends Model { ... }

那么你的表名将是:

users

forms

form_user

数据透视表应按字母顺序包含每个表的单数名称。所以 F 在字母表中出现在 U 之前,所以它应该是 form_user。

最后,在您的表单模型中,您将包含一个“belongsToMany”函数:

public function users() {
    return $this->belongsToMany('App\User');
}

在用户模型中,您可以反向包含相同的内容:

public function forms() {
    return $this->belongsToMany('App\Form');
}

如果您正确输入了迁移,您将永远不需要创建数据透视模型。您可以简单地通过关系调用其他对象来检索数组。即:

$user->forms
$form->users

【讨论】:

  • 我的模型用户看起来像这样:class User extends Authenticatable{...} 因为它是由 Jetstream Livewire 生成的,这是一个问题吗?
  • 不... User 类通常扩展 Authenticatable。如果您遵循我上面解释的命名约定,则不需要枢轴模型。
  • 这正是我所做的,但是当我的迁移具有相同的名称但末尾带有“s”字符时,我有一个错误告诉我我没有名为 forms_user 的数据透视表跨度>
  • 迁移中的数据透视表应该是按字母顺序排列的两个类名,中间加下划线。所以是的...既然您将 Forms 类命名为复数,那么迁移中的数据透视表应该是 forms_user。
  • 错误:SQLSTATE[42S02]: Base table or view not found: 1146 Table 'MyDB.forms_user' 不存在(SQL: select users.*, forms_user.@987654328 @ as pivot_forms_id, forms_user.user_id as pivot_user_id from users inner join forms_user on users.id = forms_user.forms_userforms_user哪里= 31 和users.deleted_at 为空)(查看:/home/user/public_html/V8Form/resources/views/groupes/list.blade.php)
【解决方案2】:

经过大量的努力,我终于能够解决问题,因此我没有通过 Models pivot 存储数据,而是直接通过迁移请求来完成。

无论如何,感谢您的参与。 问题解决了!

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 2021-08-23
    • 2020-05-25
    • 2018-05-31
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2020-04-13
    相关资源
    最近更新 更多