2015-09-08 42 views
1

我有两个表如何在laravel中使用关系存储数据?

帖子

id|post_title|post_content 

post_images

id|images|post_id 

控制器

public function AddPost(Request $request) 
    { 
     Post::create($request->all()); 
     // PostImage::create(); 
     return Redirect::to('Post'); 
    } 

此外,我已经添加关系

class Post extends Model 
{ 
protected $table = 'posts'; 

    public function images() 
    { 
     return $this->hasMany('App\PostImage'); 
    } 
} 


class PostImage extends Model 
{ 
    public function post() 
    { 
     return $this->belongsTo('App\Post'); 
    } 
} 

我有一种形式中,其中i后加入标题,文章内容和选择多个图像。我的问题是,我可以如何将帖子图像与帖子ID一起存储在post_images表中?

回答

1

在您控制器AddPost功能的尝试(使用表单模型绑定)

$post = new Post($request->all()); 
    PostImage::post()->images()->save($post); 

或者你也可以像这样我觉得

public function AddPost(Post $post, Request $request) 
{ 
    $input = Input::all(); 
    $input['post_id'] = $post->id; 
    PostImage::create($input); 
    return Redirect::to('Post'); 
} 
+0

@ JLPuro.ok我会try.thank你的回答 – iCoders

+0

如果你有兴趣..找到一个简单的教程,你可以为练习做。 https://www.flynsarmy.com/2015/02/creating-a-basic-todo-application-in-laravel-5-part-1/ – JLPuro

相关问题