如何使用关系插入数据?

时间:2015-09-09 05:20:36

标签: php 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');
    }
}

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

1 个答案:

答案 0 :(得分: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 还将您的数据保存到数据库 returns the object 然后   您访问 relation images 并将数据保存到 images

有关详细信息,请参阅此处One To Many