简体   繁体   English

Laravel 5.2雄辩的ORM具有许多优势

[英]Laravel 5.2 Eloquent ORM hasManyThrough

In my laravel 5.2 web app I have the following three tables- 在我的laravel 5.2网络应用程序中,我有以下三个表-

users 使用者

id
username

profiles 型材

id
user_id

profile_images 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 User.php

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

Profile.php Profile.php

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

ProfileImage.php 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. 我的问题当我在User模型上调用profile_images()时,我仅获得用户数据,并且仅返回概要文件和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. 即使我有一个配置文件(与我的测试用例匹配的user_id)和两个具有匹配的profile_id的profile_images,也没有返回任何属性/数据。

Can you help? 你能帮我吗? I'm assuming it's a problem with my hasManyThrough usage. 我假设hasManyThrough用法存在问题。

Thanks 谢谢

No. Your hasManyThrough ralation are fine, but when you call profile_images method it returns QueryBuilder instance. 不可以。hasManyThrough关系很好,但是当您调用profile_images方法时,它将返回QueryBuilder实例。 To get Collection of related models use get method 要获取相关模型的集合,请使用get方法

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

or just use laravel's "magic" 或仅使用laravel的“魔术”

$images = $user->profile_images;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM