eloquent - Laravel Relationship: Fetch child and its Parent from same table -
i have been using laravel 5.4 few weeks now. trying hands on laravel relationships. i'm trying fetch record , relation category record. want parent of fetched category using same relation.
category table:
-------------------------------------------- | id | name | parent_id | |------------------------------------------| | 1 | deals | 0 | |------------------------------------------| | 2 | dining | 1 | --------------------------------------------
deals table:
-------------------------------------------- | id | title | category | |------------------------------------------| | 1 | first deal | 2 | --------------------------------------------
i have added relationship in deal , category models
deal model:
class deal extends model { public function category() { return $this->hasone(category::class, 'id', 'category'); } // fetching deal public function fetchdeals($id = false) { $deal = deal::with('category')->get(); }
category model:
class category extends model { public function deals() { return $this->hasmany(deal::class, 'category'); }
i'm able fetch deal , relation category. not able grab parent of category.
i tried reading through few possible similar sof questions: similar 1, similar 2, similar 3. cant figure relation concept. how write above relation both parent , child category of deal.
you suggest reference article can refer.
please guide.
i have been on task few days , after reading through few articles , tutorials, have decided implement baum package
the doc easy many handy methods. easy traverse , manipulate through , parent ids of category. also, found few helpful videos on same.
hope similar requirement find helpful. cheers !!
Comments
Post a Comment