【问题标题】:Seeding Relationship one to many in Laravel在 Laravel 中一对多播种关系
【发布时间】:2019-01-05 16:25:37
【问题描述】:

我需要在 Laravel 中建立关系,每个用户都有很多设备

用户模型

public function devices()
{
    return $this->hasMany(Device::class);
}

设备模型

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

}

device_user 表

    Schema::create('device_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('device_id')->unsigned()->index();
        $table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

播种机

    factory(App\Device::class, 20)->create()->each(function(App\Device $device) {
        $device->users()->attach([
            rand(1,5), 
            rand(6,15), 
            rand(16,20), 
        ]);
    });

但是,当我使用播种机运行迁移时,我收到了这条消息

    Call to undefined method Illuminate\Database\Query\Builder::attach()

请帮忙

【问题讨论】:

    标签: php laravel relationship seed


    【解决方案1】:

    附加多对多关系,一对多关系不需要 device_user 表,在一对多中,您应该在设备表中创建一个名为 user_id 的列,仅此而已。之后,您可以使用 user_id 在设备表中插入数据。并获得用户关系

    Device::user()->get();
    

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 2017-12-29
      • 2015-12-23
      • 1970-01-01
      • 2016-05-28
      • 2021-10-29
      • 2021-05-08
      • 2017-11-24
      • 2020-02-24
      相关资源
      最近更新 更多