Laravel - 从附加输入插入多个模型

时间:2015-11-26 16:53:47

标签: laravel laravel-5 eloquent laravel-5.1

我是Laravel的新手,我正在尝试从n个附加的html输入中插入n个模型 Laravel的'Eloquent有比这更好的方法吗?

public function store(Request $request, Domain $domain, Server $server)
{
    $new_domain = $domain->create($request->all());
    $server->fill($request->only(['srv_hostname','srv_ip','srv_port']));
    $servers = array();
    $total = count($server['attributes']['srv_hostname']);
    for ($i=0;$i<$total;$i++){
        $p = new Server;
        $p->domain()->associate($new_domain);
        $p->srv_hostname = $server['attributes']['srv_hostname'][$i];
        $p->srv_ip = $server['attributes']['srv_ip'][$i];
        $p->srv_port = $server['attributes']['srv_port'][$i];
        $p->save();
    }
    return redirect()->route('domains.index');
}

1 个答案:

答案 0 :(得分:2)

不是单独保存每个服务器,而是使用单个查询保存它们:

DomainController.php

public function store(Request $req)
{
    $domain = Domain::create($req->only('domain_name'));
    $servers = [];

    foreach ($req->only('servers') as $server) {
        $s = new Server();
        $s->hostname = $server['hostname'];
        $s->ip = $server['ip'];
        $s->port = $server['port'];

        $servers[] = $s;
    }

    $domain->servers()->saveMany($servers);

    return redirect()->route('domains.index');
}

create.blade.php

<form method="POST" action="{!! route('domain.store') !!}">
  {!! csrf_field() !!}

  <input type="text" name="servers[0][hostname]">
  <input type="text" name="servers[0][ip]">
  <input type="number" name="servers[0][port]">
  <br>
  <input type="text" name="servers[1][hostname]">
  <input type="text" name="servers[1][ip]">
  <input type="number" name="servers[1][port]">
  <br>
  <input type="text" name="servers[2][hostname]">
  <input type="text" name="servers[2][ip]">
  <input type="number" name="servers[2][port]">
  <br>
  <button type="submit">Enviar</button>
</form>