简体   繁体   English

如何访问laravel集合中的属性值

[英]How to access properties values in laravel collection

I am getting data from multiple tables using eloquent relationship. 我使用雄辩的关系从多个表中获取数据。 here is my code: 这是我的代码:

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

        }
    }

when I return $posts I get this result: 当我返回$ 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: [ ]
}
]

here is my models: 这是我的模特:

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

}

I am getting error "Invalid argument supplied for foreach()" on this foreach($post->common_content as $xyz). 我在这个foreach上收到错误“为foreach()提供的参数无效”($ post-> common_content as $ xyz)。 How can I access the properties. 我该如何访问这些属性。 Any help would be highly appreciable. 任何帮助都会非常值得赞赏。

$post->common_content as $xyz isn't an array, so you can not iterate over it via foreach. $post->common_content as $xyz不是一个数组,所以你不能通过foreach迭代它。 To access a property within $post->common_content you can do it via $post->common_content->property_name 要访问$post->common_content的属性,可以通过$post->common_content->property_name

On you example it would be for "description": 在你的例子中,它将是“描述”:

$post->common_content->description

commonContent is a one to one relation. commonContent是一对一的关系。 It only retrieves one row instead of an array. 它只检索一行而不是数组。 So you can directly access its properties 所以你可以直接访问它的属性

echo $post->commonContent->description;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM