John Davidson

php - Laravel has_many relationships issue

0 comments
Message:


i have next issue:
I have two tables:



  1. pages


| id | title | content | description | image | status | noindex | viewed | author | template_id | created_at | updated_at |



  1. page_relations


| id | page_id | parent_id |


And my task is: i want to output pages by relationship.
For example: page 1 is parent of a page 2.


What i did:
in my model i use has_many:


  public function relation(){
return $this->hasMany(PageRelation::class , 'parent_id');
}

in my controller i add:


$pages = Pages::with('relation')->get();

But in dd() i saw that i get all pages with bound relations to that by value in page_relations table.



But... My question: what should i do to get pages by this ids in this model.
For example: i have list of pages and have relations with child pages (not only ids from page_relations) with title, desctiption ... from pages table?



My Answer:
To achieve this, you can modify your relationship method in the Pages model to include the related pages data from the pages table. You can do this by defining a relationship method that specifies the columns you want to retrieve from the related pages table.

Here's an example of how you can modify your relationship method:

php
public function relation(){
return $this->hasMany(PageRelation::class , 'parent_id')->with('childPage');
}

public function childPage(){
return $this->belongsTo(Page::class, 'page_id');
}


In this example, we added a new relationship method called `childPage` that specifies the relationship between the `PageRelation` model and the `Page` model. This will allow you to retrieve the related pages data from the pages table.

Then, in your controller, you can retrieve the pages with their related child pages data like this:

php
$pages = Pages::with('relation.childPage')->get();


This will load the pages along with their related child pages data from the pages table. You can then access the child pages data in your view by looping through the `relation` relationship and accessing the `childPage` relationship.

I hope this helps! Let me know if you have any further questions.

Rate this post

4 of 5 based on 8923 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us