具有多关系的sql种子表laravel

n8ghc7c1  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(236)

你好,我是新来拉威尔,我想种子表与多种关系这样

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');
}

}

snz8szmq

snz8szmq1#

我不能同意整体播种计划,播种必须更加坚实,有可能这一类或维尔不存在。。。
但是对于错误,它会出现,因为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)
        ]);
}

相关问题