douyu5679 2016-05-26 16:30
浏览 91
已采纳

Laravel 5.2 Eloquent ORM hasManyThrough

In my laravel 5.2 web app I have the following three tables-

users

id
username

profiles

id
user_id

profile_images

id
profile_id

To outline my scenario- a user can have one profile (one-to-one) and a profile can have many profile images (one-to-many). The models for these tables with the relevant relationship functions are-

User.php

public function profile_images(){
    $this->hasManyThrough('App\ProfileImage', 'App\Profile');
}
public function profile(){
    return $this->hasOne('App\Profile');
}

Profile.php

 public function profile_images()
{
  return $this->hasMany('App\ProfileImage');
}
public function user()
{
    return $this->belongsTo('App\User');
}

ProfileImage.php

    public function profile()
{
    return $this->belongsTo('App\Profile');
}

My Problem When I call profile_images() on the User model I only get the user data and only column names back for the profiles and profile_images. No attributes/data are returned even though I have a profile (with matching user_id to my test case) and two profile_images with matching profile_id.

Can you help? I'm assuming it's a problem with my hasManyThrough usage.

Thanks

  • 写回答

1条回答 默认 最新

  • doumei1772 2016-05-27 04:57
    关注

    No. Your hasManyThrough ralation are fine, but when you call profile_images method it returns QueryBuilder instance. To get Collection of related models use get method

    $images = $user->profile_images()->get();
    

    or just use laravel's "magic"

    $images = $user->profile_images;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化