[英]Laravel Eloquent One-To-Many
I'm new to Laravel and I'm trying to make a simple CMS system. 我是Laravel的新手,我正在尝试制作一个简单的CMS系统。 I made the following models which are one-to-many related: 我制作了以下与一对多相关的模型:
Page (id, name, blocks) 页面 (id,name,blocks)
public function blocks() {
return $this->hasMany('App\Block');
}
Block (id, name, displayName, content) 块 (id,name,displayName,content)
public function page() {
return $this->belongsTo('App\Page');
}
Now I want to create a page and set the blocks right away. 现在我想创建一个页面并立即设置块。 I'm getting a $request
object looking like this: 我得到一个$request
对象看起来像这样:
{
"name": "Page name",
"blocks": [
{
"name": "block name",
"displayName": "Display Name",
"content": "Some HTML content"
}
]
}
Now, I'm trying to save these all to the database, but I'm running in a lot of errors. 现在,我正在尝试将这些全部保存到数据库中,但我遇到了很多错误。
So far, I concluded I have to iterate over every 'block' and actually create a new Block
. 到目前为止,我总结说我必须迭代每个'块'并实际创建一个新Block
。 But I'm not exactly sure how to save it to the database. 但我不确定如何将其保存到数据库中。
Do I save the page first, then add the Blocks or first the blocks and then the page. 我先保存页面,然后添加块或首先是块,然后是页面。 I'm getting a bit confused. 我有点困惑。
First, make sure you have a page_id
column in the blocks table and the foreign key constraint like this : 首先,确保blocks表中有page_id
列,外键约束如下:
public function up()
{
Schema::create('blocks', function (Blueprint $table) {
$table->increments('id');
// your fields here
$table->integer('page_id')->unsigned();
$table->timestamps();
$table->foreign('page_id')
->references('id')
->on('pages')
->onDelete('cascade');
});
}
Second, you have to save the page first to the database, and then add to blocks to the page. 其次,您必须先将页面保存到数据库,然后将块添加到页面中。 Because you need the page_id when you create the blocks. 因为在创建块时需要page_id。
Finally, 最后,
You may use the
createMany
method to create multiple related models. 您可以使用createMany
方法创建多个相关模型。 See Laravel docs 请参阅Laravel文档
Example: 例:
$page = App\Page::create([
'name' => 'name',
]);
$blocks = $page->blocks()->createMany([
[
'name' => 'name1',
'displayName' => 'displayName1',
'content' => 'content1'
],
[
'name' => 'name2',
'displayName' => 'displayName2',
'content' => 'content2'
],
]);
// to get all blocks from the request
$blocks = $page->blocks()->createMany(request('blocks'));
Try using createMany method. 尝试使用createMany方法。 Do it like this. 像这样做。 You can refer docs . 你可以参考文档 。
$page = Page::create($request->only('name'));
$page->blocks()->createMany($request->get('blocks'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.