我在使用user_info表和userImage表进行一对一关系时遇到了一些麻烦。当我尝试上传我的图像时,它没有保存到我的数据库中,并且user_id为0.我设法在过去成功地做了一对多和一对一的关系,但没有与CRUD一起做。谁能帮我?最好给我一些例子让我参考或建议我应该怎么做。提前致谢
以下是我目前的代码: createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(这是我打印信息的地方)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php(我如何在视图中显示图片)
@foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->userImage!!}">
@endforeach
UserImage模型(表I中使用二进制格式存储在DB中)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(这是我上传图片的方式)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
答案 0 :(得分:0)
您需要查看Laravel relations以清理该代码并简化许多步骤。
更改此行
$UserImage->user_infos()->associate($user_info);
对于此
$UserImage->user_id = $user_info;
请注意,您在该方法中覆盖了$UserImage
的值。