【问题标题】:How to Inverse the Eloquent Has One and Has Many Through (laravel 5.8)?如何反转 Eloquent has one and has many through (laravel 5.8)?
【发布时间】:2019-06-24 05:40:33
【问题描述】:

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

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);
//    }

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

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

    如果您不介意为此功能安装第三方软件包,您可以使用staudenmeir/belongs-to-through 软件包。然后你应该能够像这样定义belongsToThrough 关系:

    class City extends Model
    {
        use \Znck\Eloquent\Traits\BelongsToThrough;
    
        public function country() {
            return $this->belongsToThrough(Country::class, District::class);
        }
    }
    

    【讨论】:

      【解决方案2】:

      为什么不能使用父方法?

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

      【讨论】:

      • 对不起,我想在不链接区域方法的情况下检索值;比如 $city->country->name。可能使用 hasOneThrough 是可能的。
      • @AhmedSohel:你可以使用访问器并在城市对象中定义国家本身吗?
      • 看我可以使用@php $country = \App\Hrm\Country::query()-&gt;first(); @endphp &lt;li&gt; {{ $country-&gt;name }} : @foreach($country-&gt;cities as $city) {{$city-&gt;name}} @endforeach &lt;/li&gt; @endphp从Country模型轻松检索城市数据
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多