dougongyou7364 2019-03-17 15:06
浏览 342
已采纳

PHP / Laravel - Foreach存储到数据库中(\ Grammar :: parameterize()错误)

I have an array, which looks like this:

array:3 [▼
  "field" => array:2 [▼
    0 => "fromName"
    1 => "from"
  ]
  "operator" => array:2 [▼
    0 => "="
    1 => "="
  ]
  "value" => array:2 [▼
    0 => "Oliver"
    1 => "oliver@mywebsite.com"
  ]
]

I am trying to save the above array, into my database table called email_rules:

My database table

Below is my code.

StreamEmailRulesController.php:

public function store(Stream $stream)
{
    //Validate the request.
    //Validate the request.
    $attributes = request()->validate([
        'field' => 'required|array|min:1',
        'field.*' => [
            'required', 'string',
            Rule::in(['fromName', 'from']),
        ],
        'operator' => 'required|array|min:1',
        'operator.*' => [
            'required', 'string',
            Rule::in(['=', '!=', 'matches']),
        ],
        'value' => 'required|array|min:1',
        'value.*' => 'required|string|min:3|max:255',
    ]);

    //Add the document to the database.
    $stream->addRules($attributes);

    //Return back.
    return redirect()->back();
}

Now the $stream->addRules() function is responsible for saving the data to the database.

Stream.php:

/**
* A stream can have many rules.
*/
public function rules()
{
    return $this->hasMany(EmailRule::class);
}


/**
 * Add Email Rules(s) to the stream
 *
 * @return Illuminate\Database\Eloquent\Model
 */
public function addRules(array $attributes)
{
    return $this->rules()->create($attributes);
}

Now, above does not work. I get below error:

Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, int given, 

What am I doing wrong?

  • 写回答

3条回答 默认 最新

  • doudong4532 2019-03-17 17:11
    关注

    The problem was that Laravels create or createMany expect an array with key => pair values, where the key corresponds to the database columns.

    This article from Adam Wathan helped me out a lot.

    This is what I ended up doing:

      $requestData = collect(request()->only('field', 'operator', 'value'));
      $rules = $requestData->transpose()->map(function ($ruleData) {
             return new EmailRule([
                 'field' => $ruleData[0],
                 'operator' => $ruleData[1],
                 'value' => $ruleData[2],
             ]);
      })->toArray();
    
      //Add the rules to the database.
      $stream->addRules($rules);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,