如何使用关系插入数据


How to insert data using relation?

我有两个表

文章

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');
    }
}

我有一个表单,其中我添加帖子标题,帖子内容和选择多个图像。我的问题是如何在post_images表中存储post图像和post id ?

像这样重写你的代码

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