【问题标题】:Get resources with hasManyThrough a model using BelongsTo通过使用 BelongsTo 的模型通过 hasManyThrough 获取资源
【发布时间】:2019-02-15 07:23:23
【问题描述】:

我有以下型号:

User:
- id
- name

Location:
- id
- name
- region_id

table: user_location
- user_id
_ location_id

用户通过该表属于ToMany 位置。我还有另一个模型:

Region
- id
- name

我定义了 Region hasMany Locations。

通过这些关系,我如何定义 User 和 Region 之间的关系,哪个 Region 将能够找到与其关联的所有 Locations 下的所有用户?

<?php 

class User extends Model
{
    public function locations() {
        return $this->belongsToMany('App\Location', 'user_location');
    }
}

class Location extends Model
{
    public function users() {
        return $this->belongsToMany('App\User', 'user_location');
    }

    public function region() {
        return $this->belongsTo('App\Region', 'region_id');
    }
}

class Region extends Model
{
    public function locations() {
        return $this->hasMany('App\Location', 'region_id');
    }

    public function users() {
        // what am I supposed to put in here?
    }
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    这种情况下没有原生关系。

    我为这样的情况创建了HasManyThrough 关系:Repository on GitHub

    安装后,可以这样使用:

    class Region extends Model {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function users() {
            return $this->hasManyDeep(User::class, [Location::class, 'user_location']);
        }
    }
    

    【讨论】:

    • 是否支持预加载?
    • 是的,它确实支持预加载。
    猜你喜欢
    • 2017-03-19
    • 2014-06-15
    • 2015-02-12
    • 2015-04-17
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    相关资源
    最近更新 更多