laravel 无法存储带有问题的标记:给定字符串

6yoyoihd  于 2023-02-05  发布在  其他
关注(0)|答案(2)|浏览(115)

我想在我的项目中存储带有问题的标签,问题和标签之间的关系是多对多的多态(多是因为我有另一个表,它们也有标签字段)
在我的**QuestionController()**中,当我想存储问题和标记时,我得到了这个错误:
传递给Illuminate\Database\Eloquent\Relations\BelongsToMany::保存()的参数1必须是Illuminate\Database\Eloquent\Model的示例,给定字符串
当我使用save而不是saveMany()时,会出现以下错误:
“message”:“传递给Illuminate\Database\Eloquent\Relations\BelongsToMany::保存()的参数1必须是Illuminate\Database\Eloquent\Model的示例,并给出数组
我也使用了sync(),但是标签没有存储在数据库中。
我和 Postman 一起尝过。
method是这样的:

public function store(StoreQuestionRequest $request)
    {
        $validatedData = $request->all();

      ////Because there is no need storage images and question codes

        $question = Question::create($validatedData); //store question

        //store tags
        $tag = new Tag();

        $tags = explode(",", $request->tag);//separate tags

        $tag['tag'] = $tags;

        $question->tags()->saveMany($tags);

        return response()->json([
            'success'=>true,
            'message'=> 'successfully',
            'data'=>$question
        ]);
    }

如果你想了解relations,这些是我的模型:

Question

public function tags(){
        return $this->morphToMany(Tag::class, 'taggable');
    }

Tag

public function questions(){
        return $this->morphedByMany(Question::class, 'taggable');
    }
3j86kqsm

3j86kqsm1#

尝试attach(),但您需要传递标记的id,而不是标记本身。
如果用户只是在标签之间进行选择,那么您可以将他选择的标签的id作为数组与请求中的问题一起发送,然后将其传递给attach方法

$question->tags()->attach($request->tagsIds);

如果用户创建了标记,您可以收集新的ID并将其传递给附件,如下所示

$tags = explode(",", $request->tag);//separate tags
$tagsIds = [];
foreach($tags as $tag)
{
 array_push($tagsIds,Tag::create(['theTagColumn ex: name'=>$tag])->id);
}
$question->tags()->attach($tagsIds);

希望这对你有用

kmynzznz

kmynzznz2#

它解决了:

public function store(StoreQuestionRequest $request)
    {
        $validatedData = $request->all();

      ////Because there is no need storage images and question codes

        $question = Question::create($validatedData); //store question

        //store tags

       $tagNames = explode(",", $request->tag);//separate tags

        $tagIds = [];

        foreach($tagNames as $tagName)
        {
            $tag = Tag::firstOrCreate(['tag'=>$tagName]);
            if($tag)
            {
              $tagIds[] = $tag->id;
            }
        }
        $question->tags()->sync($tagIds);

        return response()->json([
            'success'=>true,
            'message'=> 'successfully',
            'data'=>$question
        ]);
    }

相关问题