【问题标题】:Problem with chaining relationships in LaravelLaravel 中的链接关系问题
【发布时间】:2020-12-15 02:11:37
【问题描述】:

我有三个模型和关系。发布,用户配置文件,用户。我需要从用户表中获取名称列值,但我需要通过帖子和用户配置文件来获取它。帖子与用户个人资料相关联,用户个人资料与用户相关联。我试过 $post->userProfile()->user()->name 但它不起作用。我得到错误

Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::user()

这是我的代码。任何帮助表示赞赏。

Post.php

posts 表有 user_profile_id 列

public function userProfile()
{
    return $this->belongsTo(UserProfile::class);
}

用户配置文件.php

public function user()
{
    return $this->belongsTo(User::class, 'id');
}

public function posts()
{
    return $this->hasMany(Post::class);
}

用户.php

public function profile()
{
    return $this->hasOne(UserProfile::class, 'id');
}

【问题讨论】:

  • 什么是$posts?单个帖子还是收藏?
  • @Lessmore Single post.
  • 如果 profile() 在 User.php 中更改为 userProfile() 会发生什么
  • 不要使用括号,使用$post->userProfile->user->name

标签: php laravel


【解决方案1】:

您可能希望使用动态属性来访问实际解析的关系(模型或集合)而不是关系方法:

$post->userProfile->user->name

这将假定这些关系已正确设置并存在于数据库中。

如果您使用的是 PHP8,则可以使用存在运算符来避免关系返回 null 并在其上调用方法的问题:

$post->userProfile?->user?->name

【讨论】:

    【解决方案2】:

    请试试这个。

    // Lets get the post having id 1
    $post = Post->find(1);
    $post->userProfile->user->name;
    

    当您使用括号时,您将获得 Eloquent 关系本身,而不是该关系的结果。

    $post->userProfile();

    如果您想使用括号获取该帖子的用户个人资料信息,请使用此代码。

    $post->userProfile()->get(); //or
    $post->userProfile()->first();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 2013-04-03
      • 1970-01-01
      • 2017-02-07
      • 2014-04-18
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多