php - 如何反转 Eloquent Has One 和 Has Many Through (laravel 5.8)?

标签 php mysql laravel eloquent

下面附有三个关系表。

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

我还有三个独立的模型,其中定义了所有表之间的关系。我可以使用 hasManyThrough() 关系从国家/地区模型中读取城市模型的信息,但无法从城市模型中读取国家/地区信息。我尝试使用“hasManyThrough”检索城市模型,但没有得到结果(附加为注释国家方法)。请阅读我的模型及其关系方法。

有人可以帮助我使用 Eloquent 方法 hasManyThrough/hasManyThrough 或使用 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);
//    }

最佳答案

Laravel 中似乎还没有一种本地方法来定义“hasManyThrough”关系的逆关系。有几个issues在github上打开请求它,但他们被关闭了。

您可以使用staudenmeir/belongs-to-through包(如果您不介意为此功能安装第三方包)。然后您应该能够定义一个 belongsToThrough 关系,如下所示:

class City extends Model
{
    use \Znck\Eloquent\Traits\BelongsToThrough;

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

关于php - 如何反转 Eloquent Has One 和 Has Many Through (laravel 5.8)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56730418/

相关文章:

laravel - api 中的验证在 postman 中不适用于我的 laravel 项目

php - 多对多关系 ERD

php - 从 MySQL 数据库中提取三个即将发生的事件

php - 使用 PHP curl 和 CSRF token 登录

sql 语句检索给定记录的结果列表(从其他表)?

PHP-Laravel : Raw Sql Query showing Error in controller

python - 使用Python和odo模块在mysql上加载csv时出错

mysql - Laravel 表拒绝在迁移表上注册并回滚或迁移

javascript insidehtml 不会将变量发送到链接

php - 生成随机值并跟踪它们的总和