【问题标题】:Laravel 5.2 Eloquent ORM hasManyThroughLaravel 5.2 Eloquent ORM hasManyThrough
【发布时间】:2016-09-24 18:53:06
【问题描述】:

在我的 laravel 5.2 网络应用程序中,我有以下三个表-

用户

id
username

个人资料

id
user_id

profile_images

id
profile_id

概述我的场景 - 用户可以有一个个人资料(一对一),一个个人资料可以有许多个人资料图片(一对多)。这些具有相关关系函数的表的模型是-

用户.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');
}

我的问题 当我在用户模型上调用 profile_images() 时,我只获取用户数据,并且只获取配置文件和 profile_images 的列名。即使我有一个配置文件(与我的测试用例匹配的 user_id)和两个具有匹配 profile_id 的 profile_image,也不会返回任何属性/数据。

你能帮忙吗?我假设这是我使用 hasManyThrough 的问题。

谢谢

【问题讨论】:

  • 你能运行get方法吗?像这样的东西。 $user->profile_images()->get();

标签: php mysql orm laravel-5 eloquent


【解决方案1】:

没有。您的 hasManyThrough 合理性很好,但是当您调用 profile_images 方法时,它会返回 QueryBuilder 实例。要获取相关模型的集合,请使用get 方法

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

或者只是使用 laravel 的“魔法”

$images = $user->profile_images;

【讨论】:

  • 非常感谢 - 现在可以使用 $user->profile_images()->get();。 $user->profile_images;不起作用,但我相信这将是由于我的表/列命名约定,因此需要定义 hasManyThrough() 中使用的键。但我很高兴使用 get()。
猜你喜欢
  • 2016-08-21
  • 2014-08-14
  • 2014-10-31
  • 2020-03-07
  • 2020-10-14
  • 2016-09-26
  • 2021-01-19
  • 2019-03-26
  • 2015-07-27
相关资源
最近更新 更多