我想将所有数据从post
表移到CityPost
表中,我使用foreach
,但是为什么只有一个数据条目
$store = new CityPost;
$post = Post::all();
foreach($post as $p){
$store->user_id = 14;
$store->title = $v->title;
$store->desc = $v->desc;
$store->save();
}
dd($store);
我希望user_id
表中的所有PostCity
都为14
答案 0 :(得分:4)
您应该在foreach中创建CityPost模型:
$post = Post::all();
foreach($post as $p){
$store = new CityPost;
$store->user_id = 14;
$store->title = $v->title;
$store->desc = $v->desc;
$store->save();
}
dd($store);
答案 1 :(得分:1)
您可以做的是尝试以下类似的方式
var f = new Form();
f.Controls.Add(new Label() { Name = "x1" });
f.Controls.Add(new Label() { Name = "y" });
f.Controls.Add(new Label() { Name = "x2" });
f.Controls
.Cast<Control>()
.Where(c => c.Name.StartsWith("x")).ToList()
.ForEach(c => f.Controls.Remove(c));
Debug.Assert(f.Controls.Count == 1);
或者您可以尝试另一种方式,例如批量更新,而无需多次调用 DB
$post = Post::all();
$stores = [];
foreach($post as $p){
$store = new CityPost;
$store->user_id = 14;
$store->title = $v->title;
$store->desc = $v->desc;
$stores[] = $store->save();
//if $store->save() is boolean then you can use create method use save() or create() only one
$new = CityPost::create(['user_id'=>14,'title'=>$p->title,'desc'=>$p->desc]);
$stores[] = $new;
}
dd($stores);