Home > Software engineering >  Laravel has_many relationships issue
Laravel has_many relationships issue

Time:06-29

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.

enter image description here

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?

CodePudding user response:

You could use a HasManyThrough relation. In your case, Page has many Page through PageRelation. I think the docs will provide you with your answer - link.

On another note, there are other ways of handling that type of relation using a parent_id field on itself.

// pages migration

// schema function
$table->id();
$table->string('page_name')
$table->unsignedInteger('parent_id')->nullable();
$table->timestamps();
// end schema function
// Page.php
public function children()
{
    return $this->hasMany(Page::class, 'parent_id', 'id');
}

I normally use this when the dataset will not be huge, instead of having an intermediary table. Hope this helps.

CodePudding user response:

I had solve it by that:

public function relation(){
    return $this->hasManyThrough(
      Pages::class,
      PageRelation::class,
      'parent_id', // Foreign key on the PageRelation table...
      'id', // Foreign key on the Pages table...
      'id', // Local key on the projects table...
      'page_id' // Local key on the environments table...
    );
  }
  • Related