2016-08-24 38 views
0

海兰所有,编辑图像的ploymorphic关系

我需要更新文章的图片,它的所有罚款更新后,但我的问题是如何与我的多态性有关更新这个帖子的形象。

我有一个表与imageable_id imageable_type路径的图像。

在我的岗位控制器更新功能,我有

public function update($id) 
{ 
    $inputs = Input::all(); 

    $rules =array(
     'name'=>'required|min:5', 
     'description'=>'required|min:10', 
    ); 

    $validation = Validator::make($inputs,$rules); 

    if($validation->fails()){ 
     return Redirect::to('posts/'.Input::get('id').'/edit')->withInput() 
      ->withErrors($validation) 
      ->with('alert_error','Veuillez corriger les érreurs SVP'); 
    } 

    if(Input::hasFile('mediafile')){ 
     $file = Input::file('mediafile'); 
     $name = date('Ymd') . '-' . $file->getClientOriginalName(); 
     $file = $file->move('img/uploads/', $name); 

     $path = $file->getRealPath(); 

     //take the path only at the img not totally 
     $pos = strpos($path,'/img/'); 
     if ($pos !== false) { 
      $path = substr($path, $pos + 1); 
     } 
     $input['file'] = $path; 

     $post=Post::find(Input::get('id')); 
     $post->name  = e(Input::get('name')); 
     $post->description = e(Input::get('description')); 
     $post->category_id = e(Input::get('categories')); 
     $post->tag_id  = e(Input::get('tag')); 
     $post->rating  = e(Input::get('rating')); 
     $post->content  = Input::get('content'); 
     $post->is_online = e(Input::get('online')); 
     $post->images->path = e(Input::get('mediafile')); 

     $post->save(); 

    } 

} 

我的模型后

public function images(){ 

return $this->morphMany('Image','imageable'); 
} 

所以我想更新我的形象的唯一路径在我的表图片时,我提出我的形式展现邮政的新照片。

感谢对帮助

回答

0

的morphMany将返回图像的集合,所以当你运行$后>图像 - >路径你设置在收集路径属性不上的图像模式。如果某个帖子只是为了创建一个图片,请将其更改为morphOne,或者您必须标识要从该收藏夹更新的图片模型。

+0

我不确定要了解如何使用morphone进行更新。最好的做法是只为编辑图像的后期建立一个新的功能在我的后期模型morphone?谢谢 – nicolassiuol

+0

morphOne和morphMany之间的区别是基于您的模型之间的关系。在你的Post模型中,你指定一个帖子有很多图片,但是在你的Post控件中,你正在使用post-> image,就好像一个帖子有一个图片。如果它是一对一的关系,只需将morphMany更新为morphOne,或者如果它意味着一对多的关系,post->图像将返回一个集合。如果是这样的话,你将不得不找出你想要更新的图像。希望有帮助(https://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations) – Requisit