【问题标题】:Property [***] does not exist on this collection instance Laravel eloquent relationship此集合实例上不存在属性 [***] Laravel eloquent 关系
【发布时间】:2017-08-01 06:51:34
【问题描述】:

在我的帖子模型中

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

在用户模型中

public function posts()
{
    return $this->hasMany('App\Post');
}

现在我正在尝试获取特定用户的 cmets

$user= User::where('name', 'like', '%Mat%')->first();
return $user->posts->comment;

但它显示

此集合实例上不存在属性 [comment]。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    用户has many posts 因此返回一个集合,你需要循环这个来取出你的cmets。 IE。

    $user = User::where('name', 'like', '%Mat%')->first();
    
    $user->posts->each(function($post) {
        echo $post->comment;
    });
    

    documentation on Laravel Collections

    【讨论】:

      【解决方案2】:

      我想你可以试试这个:

      $user= User::with('post')->where('name', 'like', '%Mat%')->get();
      
      $postComment = array();
      
      foreach($user->post as $post){
        $postComment = $post->comment;
      }
      return $postComment;
      

      希望对你有帮助!!!

      【讨论】:

        【解决方案3】:

        如果你想拥有所有 cmets,你可以使用以下代码:

        $comments = [];
        
        $user = User::where('name', 'like', '%Mat%')->with(['post.comment' => function($query) use (&$comments) {
            $comments = $query->get();
        }])->first();
        
        return $comments;
        

        【讨论】:

          【解决方案4】:

          此集合实例上不存在属性 [comment]。

          出现上述错误是因为 Posts 函数返回一个集合。现在您必须遍历集合的每个元素。

          由于您返回的是 $user->posts()->comment,我假设您需要以数组的形式使用它,而不必简​​单地逐个回显它们。因此,您可以将它们全部存储在一个数组中,然后随心所欲地处理它。

          $comments = array();
          $user->posts()->each(function $post){
              $comments = $post->comment;
          }
          return $comments;
          

          为了更深入地了解这个收集功能,请阅读: https://laravel.com/docs/5.4/collections#method-each

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-25
            • 2020-07-11
            • 2019-07-10
            • 1970-01-01
            • 1970-01-01
            • 2021-07-23
            • 2021-09-07
            相关资源
            最近更新 更多