doqw89029 2015-11-24 15:59
浏览 81
已采纳

Laravel - 使用单个表单将数据发布到多个表

Let's say I have this form (linked to a named route) that contains 3 text inputs :

{!! Form::open(['route' => 'domain.store'])!!}
{!!  Form::text('srv_prefix',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('srv_ip',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::text('domain',null, $attributes = array('class' => 'form-control input-md')) !!}
{!!  Form::submit('create') !!}

the route calls this function on my controller:

public function store(CreateDomainRequest $request, Domain $domain)
{
    $domain->create($request->all());
    return redirect()->route('domain.index');
}

Always as example, let's say I have 2 tables : domains to store my domains, and servers to store my servers info (1st and second text input) actually I managed to do the inserts on my first table using the controller mentioned above. my question is how can I do the inserts on the 2 tables via a single submit on my form? how to deal with a Request and a controller for each table ?

this is what i did so far :

1 - i have already have 2 related models (Serverand Domain):

Class Server extends Eloquent {
    public function domain(){
    return $this->belongsTo('Domain');
    }
// $fillable and stuff..
}

-

Class Domain extends Eloquent {
    public function servers(){
    return $this->hasMany('Server');
    }
//
}

2 - I'm using eloquent, and my tables are related.

    Schema::table('servers', function($table){
        $table->foreign('id_domain')
            ->references('id_dom')
            ->on('domains')
            ->onDelete('cascade');
    });

The documentation does not show how to insert related models using a form. thanks for your help :)

  • 写回答

1条回答 默认 最新

  • duan20145 2015-11-24 17:41
    关注

    Here is how I would handle this. I'm assuming srv_prefix and srv_ip both are attributes of Server.

    public function store(CreateDomainRequest $request, Domain $domain, Server $server)
    {
        // Since domain is the parent, we need to start there.
        $domain = $domain->create($request->all());
    
        // Now you can create the server model
        $server->fill([
            'prefix' => \Input::get('srv_prefix'),
            'ip' => \Input::get('srv_ip')
        ]);
    
        // Now we can attach the server to the domain
        $domain->servers()->save($server);
    
        return redirect()->route('domain.index');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography