gpt4 book ai didi

php - 传递给 HasOneOrMany::save() 的 Laravel 参数 1 必须是给定的模型数组的实例

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:19 26 4
gpt4 key购买 nike

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

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in S:\Documents\samdyk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 267 and defined

这是我的代码

class Skill extends Model
{
protected $fillable = ['skill_title', 'knowledge_level'];
}

class User extends Authenticatable
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];

public function skills() {
return $this->hasMany(Skill::class);
}
}

这里是 Controller 函数

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"
]
]

如您所见,我尝试保存一个数组(这很明显)。然而,即使在 laravel 文档中我也看到了这个$post = App\Post::find(1);

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

那么为什么我的代码是错误的呢?

最佳答案

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

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

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

并且您正在传递一个简单的数组。

关于php - 传递给 HasOneOrMany::save() 的 Laravel 参数 1 必须是给定的模型数组的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com