2015-09-09 57 views
2

我有兩個表如何使用關係插入數據?

帖子

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

重寫這樣

class Post extends Model 
{ 
    protected $table = 'posts'; 
    //add $fillable here 
    protected $fillable = ['post_title', 'post_content']; 

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


class PostImage extends Model 
{ 

    protected $table = 'post_images'; 
    //add $fillable here 
    protected $fillable = ['images', 'post_id']; 

    public function post() 
    { 
     return $this->belongsTo(App\Post::class); 
    } 
} 

現在在你的控制器代碼

Post::create($request->all())->images()->create($request->all()); 

這裏Post create保存您的數據還DB returns the object然後 您訪問relation images並將數據保存到images

在這裏看到更多的細節One To Many

+0

.simply superb.thank你這麼much.it工作fine.suppose如果我有多個圖像可插入多行 – iCoders

+0

我是從輸入文件 – iCoders

+0

選擇多個圖像是的,如果你有你的輸入作爲數組例如**''它也會插入多行 –