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如何循环调取规律性名称的数据
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名机械工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统
  • ¥30 matlab appdesigner私有函数嵌套整合