为什么在Laravel中存储具有关系的数据?

时间:2019-07-01 13:57:23

标签: php laravel eloquent

我有一个BlogImage模型和一个Blog模型。现在,我想知道在关系中使用create方法是否正确,以及为什么像下面这样使用它:

$blogImage = new BlogImage();
$blogImage->blog()->create([
    //this is making the blog for me
    'title' => $request->title,
    'content' => $detail,
    'category_id' => $request->category_id,
    'author' => Auth::user()->id,
    'meta_description' => $request->title,
    'meta_image' => $meta_image,
]);

此外,我想知道此方法与正常形式之间的区别是什么:

Blog::create([
    'title' => $request->title,
    'content' => $detail,
    'category_id' => $request->category_id,
    'author' => Auth::user()->id,
    'meta_description' => $request->title,
    'meta_image' => $meta_image,
]);

1 个答案:

答案 0 :(得分:2)

简而言之:在第一个示例中,您将创建Blog实例并将其链接到blogImage,但是在第二个示例中,您将仅创建Blog的实例模型。

在第二个示例中,使用Blog创建新的blogImage实例后,必须将其附加到$blogImage->blog()->attach($blog->id)

第一个示例的create方法在here中有描述,第二个示例的here在Laravel文档中有描述。

这两种方法都是正确的。使用第一个示例要短一些。