douxu0550 2017-09-15 07:59
浏览 71
已采纳

Laravel / Eloquent - 列名作为变量

Eloquent offers a handy way of passing stuff to the database

$table_name = new TableName;
$table_name->column_name = "some data";
$table_name->save();

I've got quite a lot of data from a form that needs to be validated, so I was wondering if it was possible to replace the column name with a variable, so I can put it in some loop, and get the names and data from arrays.

$table_name->$columns[$i] = $data[$i];

(though I suppose not written in that way)

Update

In the end I've gone with the following:

$table_name = new TableName;
$nameArray=[
  1 => 'form-name-1',
  ...
];
$columnArray=[
  1 => 'column_name_1',
  ...
];

for($i=1;$i<=count($nameArray);$i++){
  if(logic logic logic) $table_name->{$columnArray[$i]} = $_POST[$nameArray[$i]];
  else $table_name->{$columnArray[$i]} = NULL;
}
$table_name->save();
  • 写回答

2条回答 默认 最新

  • doutou19761022 2017-09-15 08:12
    关注

    You can do one these:

    1) Create with values

       $table_name = new TableName([
           "column_name" => "column_value"
       ]);
    

    2) Fill

    $table_name = new TableName();
    $table_name->fill([
        "column_name" => "column_value"
    ]);
    

    3) The way you suggested originally:

    $valuesMap = [
        "column_name" => "column_value"
    ];
    $table_name = new TableName();
    foreach ($valuesMap as $column => $value) {
           $table_name->{$column} = $value; //The {} are optional in this case
    }
    

    Note that to do 1 or 2 all fields you put in the array must be fillable and not guarded.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教