lundi 13 novembre 2017

Laravel Eloquent One-To-Many

I'm new to Laravel and I'm trying to make a simple CMS system. I made the following models which are one-to-many related:

Page (id, name, blocks)

public function blocks() {
    return $this->hasMany('App\Block');
}

Block (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:

{ 
   "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. 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.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ibNAoJ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire