我在下面附加了三个关系表。


https://drive.google.com/file/d/1q1kdURIwFXxHb2MgdRyBkE1e3DMug7r-/view?usp=sharing

我还有三个单独的模型,它们在所有表之间定义了关系。我可以使用hasManyThrough()关系从Country模型中读取City模型的信息,但不能从City模型中读取Country信息。我试图使用``hasManyThrough`''来检索City模型,但是没有得到结果(作为注释的国家方法附带)。请在这里阅读我的模型及其相关方法。

是否有人可以帮助我使用雄辩的方法hasManyThrough / hasManyThrough或使用hasManyThrough / hasManyThrough的反函数来获取City模型的信息?

01。

<?php

namespace App\Hrm;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Country extends Model
{
    //use SoftDeletes;
    protected $fillable = ['name','description','status'];


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


    public function cities(){
        return $this->hasManyThrough(City::class,District::class);
    }


}



02。

<?php

namespace App\Hrm;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class District extends Model
{
    //use SoftDeletes;
    protected $fillable = ['country_id','name','description','status'];


    public function country(){
        return $this->belongsTo(Country::class);
    }

    public function cities(){
        return $this->hasMany(City::class);
    }

}


3。

namespace App\Hrm;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class City extends Model
{
    //use SoftDeletes;
    protected $fillable = ['district_id','name','description','status'];

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

//    public function country(){
//        return $this->hasOneThrough(Country::class, District::class);
//    }

最佳答案

为什么不能使用父方法?

$city = City::find(1);
$country = $city->district->country();

10-07 12:38