【问题标题】:how to add data into to database with foreach in laravel如何在 laravel 中使用 foreach 将数据添加到数据库中
【发布时间】:2019-11-27 03:52:55
【问题描述】:

我想将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);

我希望PostCity 表中的所有user_id 都是14

【问题讨论】:

  • 因为您在第一次保存后只创建了一个新模型实例,所以它现在有一个 id,之后每次调用保存只是对同一记录的更新

标签: php mysql sql laravel laravel-5


【解决方案1】:

你应该在 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);

【讨论】:

    【解决方案2】:

    你可以尝试不同的方式,如下所示

    $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);
    

    或者您可以尝试其他方式,例如批量更新,而无需多次调用 DB

        $post = Post::all();
        $data = [];
        foreach($post as $p){
            $store->user_id = 14; 
            $store->title = $v->title;
            $store->desc = $v->desc;
            $data[] = ['user_id'=>$store->user_id,'title'=>$p->title,'desc'=>$p->desc];
        }
        CityPost::insert($data);
    

    【讨论】:

    • save 返回一个布尔值,在您的第一个示例中,您正在更新 $store 而不是创建新实例,这与 OP 目前在其代码中遇到的问题相同
    • 顺便说一句,save 是否返回 bool 不存在问题,它确实返回 bool ...感谢您澄清您的回答 :)
    • 我把两者都放了,所以开发者可以选择更喜欢的一个。我希望他不会同时使用这两种方法:)
    猜你喜欢
    • 2017-06-23
    • 2021-07-05
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2017-10-19
    • 2019-07-07
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多