How to fetch data from database if one model has relation with two models in Laravel

I’m trying to fetch data from database using Laravel eloquent but it returns no data. Here is the database structure

  • Region
    • id
    • name
  • District
    • id
    • name
    • region_id
  • Ward
    • id
    • name
    • region_id

So the ward doesn’t relate with district it relates with Region. How can I get ward(data)? This is how I fetch data

Area::with('region.district.ward')->get();

Models

Region.php

public function district()
    {
        return $this->hasMany(District::class);
    }

public function ward()
   {
    return $this->hasMany(Ward::class);
   }

District.php

public function region()
    {
        return $this->belongsTo(Region::class);
    }

Ward.php

public function regions()
    {
        return $this->belongsTo(Region::class);
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can eager load the descendant tables by using dot notation, when you have data like a chaining structure, like table2 => table2 => table 3

Model1::with('model2.model3')->get();

But you data is not a chaining structure, so you can achieve it by :

Region::with('district')->with('ward')->get();

Or,

Region::with(['district', 'ward'])->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x