我有两张表护照和状态以及一个数据透视表passport_statuses。我已输入护照详细信息并从下拉列表中选择状态但我无法在数据透视表中保存数据。请帮助。我的代码如下:
护照型号
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
状态模型
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
PassportController
public function create()
{
$statuses=Statuses::lists('Status_Name','id');
return view('admin.passport.create')->with('statuses',$statuses);
}
public function store(Request $request)
{
$passport=Passport::create($request->all());
$passport->status()->attach($request->input('statuses'));
return redirect('admin/passport');
}
查看
{!!Form::open(['url'=>'admin/passport'])!!}
<div class="form-goup">
{!!Form::label('Full_Name','Full Name')!!}
{!!Form::text('Full_Name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('Date_of_Birth','Date of Birth')!!}
{!! Form::input('date', 'Date_of_Birth', null, ['class' => 'form-control', 'placeholder' => 'Date']) !!}
</div>
{!!Form::label('Passport_Number','Passport Number')!!}
{!!Form::text('Passport_Number',null,['class'=>'form-control'])!!}
<div class="form-goup">
{!!Form::label('Status_Name','Status')!!}
{!!Form::select('Status_Name',$statuses,null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::submit('Add',['class'=>'btn btn-primary'])!!}
</div>
{!!Form::close()!!}
答案 0 :(得分:0)
您的Passport模型不是belongToMany
状态,而是hasManyThrough
状态。
也许你的问题就在这里。
我认为模型Passport.php
中的行应该是这样的:
public function status()
{
return $this->hasManyThrough('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
上查看BelongToMany和HasMany文档
答案 1 :(得分:0)
class Passport extends Model
{
protected $fillable=[
'Full_Name',
'Date_of_Birth',
'Passport_Number',
'comments',
'Delivered_to_owner'
];
public function status()
{
return $this->belongsToMany('App\Statuses',"passport_statuses","passport_id","statuses_id")->withTimestamps();
}
}
class Statuses extends Model
{
protected $fillable=[
'Status_Name'
];
public function passport()
{
return $this->belongsToMany('App\Passport',"passport_statuses","statuses_id", "passport_id")->withTimestamps();
}
}
belongsToMany关系获取当前Model表的第三个参数外键和相关模型表的第四个参数foreighn键
当然,你的表必须像这个passport_statuses一样,在你的例子中至少有两列statuses_id和passport_id.And,其中包含created_at和updated_at timestamp列
答案 2 :(得分:0)
我能够通过在 PassportController
中更改输入(&#39;状态&#39;)来输入(&#39; Status_Name&#39;)来解决这个问题。$passport->status()->attach($request->input('Status_Name'));