如何使用外键插入多个标签?

时间:2018-06-05 04:05:17

标签: laravel tags taglist

[提交函数][1] error message while inserting function for inserting tags错误,同时使用外键向数据库插入许多标签。我在数组中遇到问题,无法插入多个标签

 public function uploadSubmit(UploadRequest $request)
{
    $product = new Product();
    $product->name = $request['name'];
    $product->save();



    //$product = Product::create($request->all());
    foreach ($request->photos as $photo) {
        $filename = $photo->store('photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);

    }
    $tags = array();
    $tags = array($request['tagname[]']);
    foreach ($tags as $tag) {


        ProductTag::create([
            'tag_id' => $product->id,
            'tagname' => $tag,
        ]);
    }
    $message = 'Upload successful!';
    return redirect('/upload')->with('msg' , $message);
}

[环境&详情:[] [2]] [sql error 3]

1 个答案:

答案 0 :(得分:0)

好的 - 所以在了解了一下您目前的设置后,我认为您可以从以下方面重新构建它:[/ p>

  1. 模型Product拥有tags()关系方法:
  2. public function tags(): MorphToMany
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
    
    1. 添加中间表taggable
    2. php artisan make:migration create_taggables_table --create=taggables
      
      class CreateTaggablesTable extends Migration
      {
          public function up()
          {
              Schema::create('taggables', function (Blueprint $table) {
                  $table->unsignedInteger('tag_id');
                  $table->unsignedInteger('taggable_id');
                  $table->string('taggable_type');
              });
          }
      
          public function down()
          {
              Schema::dropIfExists('taggables');
          }
      }
      
      1. 更新您的控制器以添加新标签,然后将其与产品相关联:
      2. public function uploadSubmit(UploadRequest $request)
        {
            $product = new Product;
            $product->name = $request->name;
            $product->save();
        
        
            $photos = collect($request->photos)->map(function($photo) use ($product) {
                return [
                    'product_id' => $product->id,
                    'filename' => $photo->store('photos')
                ];
            })->toArray();
        
            ProductsPhoto::insert($photos);
        
        
            $tagsInUse = Tag::whereIn('name', $request->tagname);
        
            if (count($request->tagname) > $tagsInUse->count()) {
        
                $newTags = collect($request->tagname)->diff($tagsInUse->pluck('name')->values())->map(function (string $tag) {
                    return ['name' => $tag];
                });
        
                Tag::insert($newTags->toArray());
        
                $tagIds = Tag::whereIn('name', $request->tagname)->pluck('id')->values();
        
            } else {
        
                $tagIds = $tagsInUse->pluck('id')->values();
        
            }
        
            $product->tags()->attach($tagIds);
        
        
            return redirect('/upload')->with('msg' , 'Upload successful!');
        }
        

        这是对此设置的测试:

        public function test()
        {
            factory(Tag::class)->create(['name' => 'one']);
            factory(Tag::class)->create(['name' => 'two']);
            factory(Tag::class)->create(['name' => 'three']);
        
            $this->assertEquals(
                ['one', 'two', 'three'],
                Tag::all()->pluck('name')->toArray()
            );
        
        
            $requestTags = new Collection(['one', 'three', 'four', 'five']);
        
            $inUse = Tag::whereIn('name', $requestTags)->pluck('name')->values();
        
            $newTags = collect($requestTags)->diff($inUse)->map(function(string $tag) {
                return ['name' => $tag];
            });
        
            Tag::insert($newTags->toArray());
        
            $this->assertEquals(
                ['one', 'two', 'three', 'four', 'five'],
                Tag::all()->pluck('name')->toArray()
            );
        
        
            $product = factory(Product::class)->create(['name' => 'Bike']);
        
            $this->assertEmpty($product->tags);
        
        
            $tagIds = Tag::whereIn('name', $requestTags)->pluck('id')->values();
        
            $product->tags()->attach($tagIds);
        
            $this->assertEquals(
                ['one', 'three', 'four', 'five'],
                $product->fresh('tags')->tags->pluck('name')->toArray()
            );
        }
        

        参考:https://laravel.com/docs/5.6/eloquent-relationships#many-to-many-polymorphic-relations