我有两张表donor
和address
。
我想在donor
表中插入所有基本详细信息,并将地址放入带有捐赠者ID的address
表中。
<?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
表中输入详细信息。
答案 0 :(得分:1)
如果捐赠者有地址,并且地址是具有自己的表的唯一项目,则应为地址创建模型,并使用雄辩的关系将这两者连接在一起。
您可以阅读有关雄辩关系的更多信息here
所以在你的Donor模型中,你会这样:
public function address(){
return $this->hasOne('App\Address');
}
在你的地址类中:
public function donor(){
$this->belongsTo('App\Donor');
}
因此,在您的捐赠者控制器中,您将创建一个新的地址实例,并将其连接到捐赠者:
$address = new App\Address;
... Your stuff to populate the address
$donor->address()->save($address);
注意:这不是实现你想要的整个代码,而是我从内存中编写的。你应该做一些研究来搞清楚。