jeudi 22 avril 2021

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

Region::with('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);
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire