传递给HasOneOrMany的Laravel Argument 1 :: save()必须是给定的Model数组的实例

时间:2017-07-26 14:56:54

标签: php laravel model

我是 Laravel 的新手,当我尝试将数据数据保存到数据库时,我遇到了问题。这是我得到的错误

  

参数1传递给   Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()必须是   Illuminate \ Database \ Eloquent \ Model的实例,给定的数组,调用   S:\文档\ samdyk \供应商\ laravel \框架的\ src \照亮\数据库\雄辩\关系\ HasOneOrMany.php   在第267行并定义

所以这是我的代码

public function editMyProfile(Request $request) {
        $user = Auth::user();

        dump($request->get('skills'));
       // dump($request->get('skills')[0]);
        dump($user->skills()->saveMany($request->get('skills')));
       return 1;
}

这是控制器功能

$request->get('skills')

所以这里是array:5 [ 0 => array:2 [ "skill_title" => "fghjghj" "knowledge_level" => "20" ] 1 => array:2 [ "skill_title" => "gjghjhgj" "knowledge_level" => "50" ] 2 => array:2 [ "skill_title" => "ghjhgjgfjh" "knowledge_level" => "80" ] 3 => array:2 [ "skill_title" => "hjkhgkkkhgjkjhkhjgk" "knowledge_level" => "53" ] 4 => array:2 [ "skill_title" => "jghjhgjhgj" "knowledge_level" => "57" ] ] 数据

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

因此,您可以看到我尝试保存数组(这很明显)。然而,即使是laravel文档,我也看到了这一点 $ post = App \ Post :: find(1);

{{1}}

为什么我的代码错了?

2 个答案:

答案 0 :(得分:6)

您需要将Skill个对象数组传递给saveMany()方法:

$skillModels = [];
foreach ($request->skills as $skill) {
    $skillsModels[] = new Skill($skill);
}

$user->skills()->saveMany($skillModels);

你传递的是一个简单的阵列。

答案 1 :(得分:3)

只需尝试createMany:)

$post->comments()->createMany([
    ['message' => 'A new comment.'],
    ['message' => 'Another comment.'],
]);

查看文档:{​​{3}}