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

时间:2019-03-17 15:06:22

标签: php laravel

我有一个数组,看起来像这样:

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

我正在尝试将上述数组保存到名为email_rules的数据库表中:

My database table

下面是我的代码。

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();
}

现在$stream->addRules()函数负责将数据保存到数据库。

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

现在,以上操作无效。我遇到以下错误:

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

我在做什么错了?

3 个答案:

答案 0 :(得分:0)

如果您转储$ attributes,则可能会从验证中获取一个int(布尔)作为通过,失败或什至json,具体取决于进行的操作。这可能只是更改语法的问题

…\Microsoft\Windows\CurrentVersion\App Paths

HKEY_CLASSES_ROOT\Applications\

我相信您的问题是,您正在尝试将数组另存为奇异值。 IE中,需要迭代这些属性,以为每个规则创建一组新的规则 。通常,我希望看到准备好创建单个对象的数组。在这种情况下,尽管看起来它可以创建单个字段(字段,运算符,值),但是遍历这些字段可能也无法满足您的期望-它为创建提供了多个字段构造,而不是为新rule()提供全套的对象参数。我认为Laravel暗示您可能希望更改请求/返回结构以匹配模型格式。

答案 1 :(得分:0)

我认为这可能是数组结构。您可以将数组修改为吗?:

[
   [
   "field" => "fromName",
   "operator" => "=",
   "value" => "Oliver"
   ],
   [
   "field" => "from",
   "operator" => "=",
   "value" => "oliver@mywebsite.com"
   ],
]

编辑: 在控制器中添加如下所示的循环:

...
foreach ($attributes as $key => $value) {
    foreach ($value as $k => $v) {
        $data [$k][$key] = $v;
    }
}

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

答案 2 :(得分:0)

问题是Laravels createcreateMany期望一个具有key =>对值的数组,其中key对应于数据库列。

This article来自Adam Wathan,对我帮助很大。

这就是我最终要做的:

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