php - Laravel 5.2 Eloquent ORM hasManyThrough

标签 php mysql orm laravel-5 eloquent

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

用户

id
username

个人资料

id
user_id

个人资料图片

id
profile_id

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

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

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

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

谢谢

最佳答案

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

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

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

$images = $user->profile_images;

关于php - Laravel 5.2 Eloquent ORM hasManyThrough,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466427/

相关文章:

javascript - 如何将 jquery 数组值发送到 codeigniter Controller

php - UTF-8贯穿始终

php - 从数组中获取指定行

java - JPA 删除。在这种情况下,推荐的方法是什么?

java - 在 Ebean 中创建嵌套对象的最简单方法是什么?

Laravel 中的 PHPUnit 错误 : Exception' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host ' mysql' (2)'

php - Mysql 使用 while 循环选择最后 20 行

mysql - 从表中选择至少有一行符合不同要求的值

跨多个表的 MySQL 关键字搜索

php - 向 Propel 模型添加自定义列?