如何在Laravel集合中访问属性值

时间:2019-06-25 12:33:12

标签: php laravel laravel-5

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

 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()提供了无效的参数”。如何访问属性。任何帮助都是非常可取的。

2 个答案:

答案 0 :(得分:0)

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

在您的示例中,它将用于“描述”:

$post->common_content->description

答案 1 :(得分:0)

commonContent是一对一的关系。它仅检索一行而不是数组。这样您就可以直接访问其属性

echo $post->commonContent->description;