如何在Laravel中使用foreach将数据添加到数据库

时间:2019-11-27 03:52:55

标签: php mysql sql laravel laravel-5

我想将所有数据从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

2 个答案:

答案 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);