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


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_images表中存储多个图像和post-id?

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

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

您可以这样做:

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

如前所述。。。您是否尝试过使用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文档示例,但这里所要做的只是更改名称和类。机制总是一样的。

希望能有所帮助。