dongzha3058 2018-03-25 11:37
浏览 290

Laravel - 将多个字段保存为数组而不是行

I have one to many relation tables. I want to insert child table data in array instead of rows.

Mobile.php

protected $fillable = ['mobile_id', 'mobile_name'];

public function models() {
    return $this->hasMany(Model::class, 'mobile_id');
}

Model.php

protected $fillable = ['model_name', 'mobile_id'
    ];
public function model()
{
    return $this->belongsTo(Mobile::class, 'mobile_id');
}

View

Mobile Name: <input type="text" name="mobile_name">

Models:

<input type="text" name="model_name[]">
<button class="add_model">Add Model</button>

Controller

public function create(Request $request, Mobile $mob){
  $mob= new Mobile;
  $mob->mobile_name = request('mobile_name');

  for($i=0; $i < count(request('model_name')); $i++){
     $models = new Model;
     $models->model_name = request('model_name')[$i];

     $mob->models()->save($models);
     }
 $mob->save();
}

It's creates a new row for each mobile models inserted. But I want those models inserted in a single column model_name in an array line.

I tried

for($i=0; $i < count(request('model_name')); $i++){
  Size::create([
  'model_name' => request('model_name')[$i],
  'mobile_id' => $mob->id
  ]);

But it is also not working.

  • 写回答

2条回答 默认 最新

  • dongzhuo3202 2018-03-25 12:12
    关注

    You should serialize the data before saving it in the database.Create the model instance outside the for loop.Here is the working code.

       public function create(Request $request, Mobile $mob){
          $mob= new Mobile;
          $mob->mobile_name = $request('mobile_name');
          $models = new Model;
          $arr=[];
          for($i=0; $i < count($request('model_name')); $i++){
             array_push($arr, $request('model_name')[$i]);
             }
          serialize($arr);
          $models->model_name =$arr;
          $mob->models()->save($models);
         $mob->save();
        }
    

    In the model.php, add the below code

    protected $casts = [
          'model_name ' => 'array',
    ]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据