Ad

PHP: Laravel How To Create Model In Multiple One-many Relationship

- 1 answer

I have a relationship between three models in my laravel application, user model has many pages and pages has many keywords, all of which correspond to three tables on the database with same names. I want to create a user and pass along the users pages and keywords to the pages. I doubt I have any idea how to do it. What I did is below but it does not work, even when I add keywords to $fillable it throws an exception no column keywords on pages

what I did is:

        $pages  =   [
            'name' => 'mimi',
            'link' => 'mimi',
            'category' => 'trivial',
            'keywords' => [
                ['name' => 'GGG'], 
                ['name' => 'DDD']
            ]
        ];

        $user->pages()->create($pages);
Ad

Answer

You need to create the page first, than add the keywords. (not sure if the syntax is correct)

$pages  =   [
    'name' => 'mimi',
    'link' => 'mimi',
    'category' => 'trivial'
];

$keywords = ['GGG','DDD'];

$page = $user->pages()->create($pages);

foreach($keywords as $keyword) {
  $page->keywords()->create(['name' => $keyword]);
}
Ad
source: stackoverflow.com
Ad