如何使用关系插入多个数据?

How to insert multiple data using relation?

控制器

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

PostImage 型号

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

我有一种形式,我在其中添加 post 标题,post 内容并选择多张图片。我的问题是如何在 post_images table?

中存储多个图像以及 post id

你可以这样做:

Post::create($request->all())->images()->create([$request->get('images')]);

您可以在关系上使用恰当命名的 createMany() 方法:

// Create post
$post = Post::create($request->except('images'));

// Create post images
foreach ($request->get('images') as $images) {
    $post->images()->create(compact('images'));
}

之前已经 post...您是否尝试过使用 saveMany 方法?其实你也可以这么简单的使用它

Laravel 文档中的示例不言自明。

您可以使用简单的 save 方法来保存单个实例。

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$comment = $post->comments()->save($comment);

如果关系的 "many" 部分有很多实例,您可以使用 saveMany()。

$post = App\Post::find(1);

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

两种方法都会自动设置post_id值。如果你想手动设置它,你应该得到你需要的 post_id 然后像这样手动设置它。

$comment->post_id = $yourDesiredPostId;

...最后,照常保存。

$comment->save();

注意: 我使用了 Laravel 文档示例,但您在这里只需更改名称和 类。机制总是一样的。

希望对您有所帮助。