我有两个故事故事和精选故事,所以我想在单个请求中将几个故事ID添加到精选表格。怎么做?
这是我的代码,用于将单个ID添加到精选故事表中。
public function saveFeatured($id)
{
# code...
$story = $this->getById($id);
$storyId = $story->id;
$featured = new FeaturedStory();
$featured->story_id = $storyId;
$featured->save();
return "Added to featured StoryList";
}
将id的数组传递给函数,然后执行此操作。
public function saveFeatured($arrayid){
foreach($arrayid as $key => $item){
$story = $this->getById($item);
$storyId = $story->id;
$featured = new FeaturedStory();
$featured->story_id = $storyId;
$featured->save();
}
return "Added to featured StoryList";
}
签出:has-many-create-relationship
在您的Story.php模型中:
public featuredStoreis() {
return $this->hasMany(\App\FeaturedStory::class, 'story_id', 'id');
}
在您的FeaturedStory.php模型中:
public story() {
return $this->belongsTo(\App\Story::class);
}
然后您可以轻松地创建featured_storeis;
$array = ... # your featured_stories attributes array.
$story->featuredStories()->createMany($array);
这将自动填充story_id
中的FeaturedStory
您可以使用saveMany()或createMany()方法。首先,用几个项目填充一个数组,然后一次有效地存储它们。在问题的注释中也使用@Cerlin甲硫氨酸原始插入方法。
我不知道您如何获得输入以及“功能”的确切含义是什么,但看起来可能像这样:
$story->featured()->saveMany([
new App\Featured(['id' => 1, 'title' => 'First story']),
new App\Featured(['id' => 2, 'title' => 'Another story']),
]);
这是一个非常相似的问题:https://stackoverflow.com/a/33769331/272885