在Laravel中,可以使用以下步骤保存包含hasManyThrough关系的新对象:
class Country extends Model
{
public function users()
{
return $this->hasMany(User::class);
}
}
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
// ...
}
$country = new Country;
$country->name = 'USA';
// 设置其他属性...
$user1 = new User;
$user1->name = 'John';
// 设置其他属性...
$user2 = new User;
$user2->name = 'Jane';
// 设置其他属性...
$post1 = new Post;
$post1->title = 'My first post';
// 设置其他属性...
$post2 = new Post;
$post2->title = 'My second post';
// 设置其他属性...
$country->users()->saveMany([$user1, $user2]);
$country->users->each(function ($user) use ($post1, $post2) {
$user->posts()->saveMany([$post1, $post2]);
});
在这个示例中,我们使用saveMany
方法将关联的User和Post对象添加到Country对象中。注意,在保存User对象之后,我们使用each
方法遍历每个User,并将关联的Post对象添加到每个User中。
save
方法保存Country对象。$country->save();
这样,包含hasManyThrough关系的新对象就会被保存到数据库中。