php - 如何反转 Eloquent has one and has many through (laravel 5.8)?
问题描述
我在下面附上了三个关系表。
https://drive.google.com/file/d/1q1kdURIwFXxHb2MgdRyBkE1e3DMug7r-/view?usp=sharing
我还有三个单独的模型,其中定义了所有表之间的关系。我可以使用hasManyThrough()
关系从国家模型中读取城市模型的信息,但不能从城市模型中读取国家信息。我尝试使用“hasManyThrough”检索城市模型,但没有得到结果(附加为评论国家方法)。请阅读我的模型和它的关系方法在这里..
hasManyThrough / hasManyThrough
有没有人可以帮助我使用 Eloquent 方法或使用 inverse of 获取 City 模型的信息hasManyThrough / hasManyThrough
?
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();