首页 > 解决方案 > Laravel 5.2 - 使用带有数组值的附加方法

问题描述

我正在用 Laravel 5.2 中的帖子创建一个博客。每个帖子都会有多个标签。我创建了帖子和标签之间的关系。创建帖子后,我正在尝试为其附加多个标签。

控制器功能

public function store(Request $request)
{
        $attributes = [
            'author_id' => Auth::user()->id,
            'title' => $request->input('title'),
            'text' => $request->input('text'),
        ];

        $post = Post::create($attributes);

        // Get the tag ids from the the tags table in the database
        $tagsList = $request->input('tags');        
        $tags = explode(",", $tagsList);

        $tagIds = array();
        foreach($tags as $tag) {
          $tagIds[] = Tag::select('id')->where('name', $tag)->limit('5')->get();
        }

        dd($tagIds); // Output below

        $post->tags()->attach($tagIds); // not working
}

dd($tagIds) 输出

array:2 [▼
  0 => Collection {#316 ▼
    #items: array:1 [▼
      0 => Tag {#317 ▼
        #fillable: array:2 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:1 [▼
          "id" => 32
        ]
        #original: array:1 [▶]
        #relations: []
        #hidden: []
        #visible: []
        #appends: []
        #guarded: array:1 [▶]
        #dates: []
        #dateFormat: null
        #casts: []
        #touches: []
        #observables: []
        #with: []
        #morphClass: null
        +exists: true
        +wasRecentlyCreated: false
      }
    ]
  }
  1 => Collection {#318 ▼
    #items: array:1 [▼
      0 => Tag {#319 ▼
        #fillable: array:2 [▶]
        #connection: null
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:1 [▼
          "id" => 36
        ]
        #original: array:1 [▶]
        #relations: []
        #hidden: []
        #visible: []
        #appends: []
        #guarded: array:1 [▶]
        #dates: []
        #dateFormat: null
        #casts: []
        #touches: []
        #observables: []
        #with: []
        #morphClass: null
        +exists: true
        +wasRecentlyCreated: false
      }
    ]
  }
]

返回的数组包含正确的标签 ID。我只是不知道如何将它们转换为格式,以便可以将它们传递给附加方法。

我会非常感谢任何形式的帮助!

标签: phparrayslaravellaravel-5eloquent

解决方案


为方便起见,附加和分离也接受 ID 数组作为输入:

        $tagIds = array();
        foreach($tags as $tag) {
          $tagIds[] = Tag::select('id')->where('name', $tag)->first()->id;
        }

        dd($tagIds); // Output below
        /* 
       Array
       (
           [0] => 1
           [1] => 3
           [2] => 5
        )
        */

        $post->tags()->attach($tagIds); 

推荐阅读