Laravel 5.2 Eloquent - Saving data in multiple tables so that _id's are saved

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Laravel 5.2 Eloquent - Saving data in multiple tables so that _id's are saved



I have three tables: pages, headers, footers. I have relationships set up so that Page hasOne('AppFooter') and hasOne('AppHeader'). Header and Footer each belongTo('AppPage'). The pages table has header_id and footer_id. The others have page_id. When I retrieve Page, the header and footer are also pulled IF (and only if) all the id's correspond to each other.


hasOne('AppFooter')


hasOne('AppHeader')


belongTo('AppPage')


header_id


footer_id


page_id


Page



In my controller, there's no problem saving Page, including the header and footer. But since I have relationships set up, all of the ids should be correctly saved but only the page_id is being saved on the footers and headers table - the ids of the footers and headers are not being saved to the pages table. Here's what I have so far:


Page


page_id


public function putAddpage(Request $request)

$header = new Header(['text' => $request->input('header-text')]);
$footer = new Footer(['text' => $request->input('footer-text')]);

$page = new Page();
$page->title = $request->input('page-title');
$page->some_text = $request->input('some_text');
$page->save();

$page->header()->save($header);
$page->footer()->save($footer);

return $page;



Example DB data:

pages: id:12, footer_id:0, header_id:0, title:"Page Title", some_text:"blah blah blah"

footers: id:2, page_id:12, text:"More blah blah blah"

headers: id:4, page_id:12, text:"Nothing to see here"



How do I get it so the footer_id and header_id have the correct ids saved as well?


footer_id


header_id



Thanks.




2 Answers
2



Ideally you wouldn't. What I understand from your code is that header_id and footer_id shouldn't be there, you don't need them.


header_id


footer_id



if you want to get the header of a page..


$page->header;



you don't need header_id on the page table for this to work! since you defined the relationship already ( page -> hasOne header )



Are you trying to achieve different behavior?



Your relationships are reversed, they should be belongsTo relationships if the foreign key is stored with that model, or within that table.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS