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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里