从 Laravel 中的 Controller 添加数据到超过 1 table

Add data into more than 1 table from Controller in Laravel

我有两个 table donoraddress.

我想在 donor table 中插入所有基本详细信息,并使用捐赠者 ID 在 address table 中添加地址。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Donor;

class DonorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('donor.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $donor = new Donor;
        $donor->salutation = $request->input('salutation');
        $donor->gender = $request->input('gender');
        $donor->first_name = $request->input('first_name');
        $donor->last_name = $request->input('last_name');
        $donor->phone = $request->input('phone_home');
        $donor->mobile = $request->input('phone_mobile');
        $donor->email = $request->input('email');
        $donor->occupation = $request->input('occupation');
        $donor->is_active = $request->input('status');
        $donor->is_deleted = 0;
        $donor->created_by = 1;
        $donor->updated_by = 1;
        $donor->save();


        return redirect('/donor')->with('success', 'Hurray!! New donor Created.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

如何将详细信息输入 address table.

如果捐助者有一个地址,并且该地址是一个具有自己的 table 的唯一项目,您应该为地址创建一个模型,并使用 eloquent 关系连接这两个在一起。

您可以阅读更多关于 eloquent 关系 here

所以在你的 Donor 模型中,你会这样做:

public function address(){
     return $this->hasOne('App\Address');
}

在你的地址 class:

public function donor(){
     $this->belongsTo('App\Donor');
}

因此,在您的捐助者控制器中,您将创建一个新的地址实例,并将其连接到捐助者:

$address = new App\Address;
... Your stuff to populate the address
$donor->address()->save($address);

注意:这不是你想要实现的全部代码,我凭记忆写的。你应该做一些研究来弄清楚。