【问题标题】:belongsToMany on not primary field非主字段上的 belongsToMany
【发布时间】:2017-07-08 00:40:12
【问题描述】:

例如,我有 4 张桌子:
建筑物
id、标题、...
房间
id, building_id, title, ...
公司
id、标题、...
companies_to_buildings
company_id, building_id

我想从房间模型中获得公司。
从建筑模型我可以做类似的事情

class Building extends Model
{
    public function companies(){
        return $this->belongsToMany('App\Company', 'company_building');
    }
}

class Building extends Model
{
    public function companies(){
        return $this->belongsToMany('App\Company', 'company_building', 'building_id', 'company_id');
    }
}

但如果我在房间模型中执行此操作,它将无法正常工作。它将尝试在company_to_buildings 表中查找company_to_buildings.building_id=room.id 的行。如何从房间模型中获得公司?

【问题讨论】:

    标签: php eloquent many-to-many laravel-5.1


    【解决方案1】:

    您可以使用hasManyThrough

    例子:

    public function series()
    {
    return $this->hasManyThrough('Series', 'Product');
    }
    

    【讨论】:

    • 我应该在 hasManyThrought 中使用哪些模型?
      公共函数 Companies(){return $this->hasManyThrough('App\Company', 'App\Building', 'building_id', ' id', 'building_id');}
      创建查询,如
      select company.*, building.building_id from company inside join building on building.building_id=company.id where company.deleted=0 and building. building_id in (5)
      但我需要类似:
      选择公司。*,从公司内部加入 Companies_to_buildings on Companies_to_buildings.company_id=company.id where company.deleted = 0 and Companies_to_buildings.building_id in (5)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2020-06-04
    • 2011-10-22
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多