【问题标题】:How to access properties values in laravel collection如何访问 laravel 集合中的属性值
【发布时间】:2019-11-07 07:10:49
【问题描述】:

我正在使用 eloquent 关系从多个表中获取数据。这是我的代码:

 public function allPosts()
    {
        $posts = Post::with('commonContent','postComment','postLike')->get();
        //return $posts;
        foreach($posts as $post){
            echo $post->id;
            echo $post->content_id;

            foreach($post->common_content as $xyz){
              echo $xyz->description;
           }

        }
    }

当我返回 $posts 时,我得到了这个结果:

[
{
id: 2,
user_id: 8,
content_id: 3,
title: null,
created_at: "2019-06-25 10:00:41",
updated_at: "2019-06-25 10:00:41",
common_content: {
id: 3,
description: "this is a post",
media_json: "{"image":"uploads\/j658XUVMuP2dutAgNUTpYvqLABkJLwYXkgX1zTai.png","video":"uploads\/wIsZNWVDZYZYOgdGstNA5dIsexpQAUu4zJo0wp0c.mp4","audio":"uploads\/2AjXxj1NgeUnUlsCkSAgVqgrykb4XwL8sbjin3cC.mpga"}",
created_at: "2019-06-25 10:00:41",
updated_at: "2019-06-25 10:00:41",
media_json_setting: {
image: "uploads/j658XUVMuP2dutAgNUTpYvqLABkJLwYXkgX1zTai.png",
video: "uploads/wIsZNWVDZYZYOgdGstNA5dIsexpQAUu4zJo0wp0c.mp4",
audio: "uploads/2AjXxj1NgeUnUlsCkSAgVqgrykb4XwL8sbjin3cC.mpga"
}
},
post_comment: [ ],
post_like: [ ]
}
]

这是我的模型:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'user_id', 'content_id'
    ];
    public function commonContent()
    {
        return $this->hasOne('App\Models\CommonContent', 'id','content_id');
    }

    public function postComment()
    {
        return $this->hasMany('App\Models\PostComment');
    }

    public function postLike()
    {
        return $this->hasMany('App\Models\PostLike');
    }

}

我在这个 foreach($post->common_content as $xyz) 上收到错误“为 foreach() 提供的参数无效”。如何访问属性。任何帮助都将不胜感激。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    $post->common_content as $xyz 不是数组,因此您不能通过 foreach 对其进行迭代。要访问$post->common_content 中的属性,您可以通过$post->common_content->property_name 进行操作

    在你的例子中,它是“描述”:

    $post->common_content->description
    

    【讨论】:

    • 我收到错误:尝试获取非对象的属性“描述”
    【解决方案2】:

    commonContent 是一对一的关系。它只检索一行而不是一个数组。所以你可以直接访问它的属性

    echo $post->commonContent->description;
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 2017-05-28
      • 1970-01-01
      • 2018-09-03
      • 2023-03-20
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多