【问题标题】:Seeding table with multiple Relations laravel具有多个关系 laravel 的播种表
【发布时间】:2020-10-08 02:00:48
【问题描述】:

你好,我是 laravel 的新手 我想播种一个像这样具有多个关系的表

       for ($i=0; $i < 30; $i++) {
        Product::create([
            'title' => $faker->sentence(1),
            'slug' => $faker->slug,
            'subtitle' => $faker->sentence(3),
            'categorie' => $faker->sentence(1),
            'ville' => $faker->sentence(1),
            'description' => $faker->text,
            'price' => $faker->numberBetween(15, 300),
            'duration' => $faker->numberBetween(15, 300),
            'image' => '//imgur.com/a/WhaAC9O'
        ])->categories()->attach([
            rand(1, 4),
            rand(1, 4)
        ])

但是当我添加这部分时,它会在播种时引发异常

->villes()->attach([
            rand(1, 1),
            rand(1, 1)
        ])

;

这是个例外:

在 null 上调用成员函数 villes()

我该怎么办?

这是 Product.php

class Product extends Model
{


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

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

}

【问题讨论】:

  • 你是否链接了categories()->attach([ rand(1, 4), rand(1, 4) ])->villes()->attach([rand(1 ,1)]); ?
  • 在此处添加您的关系代码。所以会更好地了解那里有什么问题。
  • 我正在尝试将产品链接到类别以及将产品链接到 Ville

标签: sql laravel exception seed laravel-seeding


【解决方案1】:

我不能就整体播种计划达成一致,播种必须更扎实,有可能这个类别或村庄不存在......

但对于错误,它会显示出来,因为attach 方法返回 null

for ($i=0; $i < 30; $i++) {
  $product=  Product::create([
        'title' => $faker->sentence(1),
        'slug' => $faker->slug,
        'subtitle' => $faker->sentence(3),
        'categorie' => $faker->sentence(1),
        'ville' => $faker->sentence(1),
        'description' => $faker->text,
        'price' => $faker->numberBetween(15, 300),
        'duration' => $faker->numberBetween(15, 300),
        'image' => '//imgur.com/a/WhaAC9O'
    ]);
$product->categories()->attach([
            rand(1, 4),
            rand(1, 4)
        ]);
$product->villes()->attach([
            rand(1, 1),
            rand(1, 1)
        ]);
}

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2021-05-13
    • 2016-05-28
    • 2020-10-04
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2019-01-05
    相关资源
    最近更新 更多