dongqishou7471 2015-11-05 14:45
浏览 7

获取关系数据的最佳方法是什么?

I need some help to find out a best way to fetch data from following table structure.

Table One: organisations id name etc.

Table Two: locations id name etc.

Table Three: organisaiton_locations this table holds the relation as follows:

id | organisation_id | location_id
  • id: auto-increment
  • organisation_id foreign key reference to id on organisations table
  • location_id foreign key reference to id on locations table

Whey I try this with hasManyThrough, I get the correct number of items but they are mapped to id instead of location_id.

class Organisation extends Model
{

    public function locations()
    {
        return $this->hasManyThrough('App\Models\Location', 'App\Models\OrganisationLocation', 'organisation_id', 'id');
    }

}

Can you please help me understand how can I fetch all locations related to an organisation in a collection so that can be used in a transformer.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • duanhong8839 2015-11-05 16:03
    关注

    You don't have to use hasManyThough just use the normal one, with through you are trying to access third level relation, where in your case it's not.

    Simply replace it with:

    class Organisation extends Model
    {
    
         public function locations(){
             return $this->hasMany(Location::class,'organisaiton_locations', 'organisation_id', 'location_id')->withTimestamps();
         }
    
    }
    

    and please remember to import your Location class (first argument in hasMany function) or just use it as string, the way you did

    if you don't have timestamps in your junction table then remove this from the end of the above code ->withTimestamps()

    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来