【发布时间】: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() 提供的参数无效”。如何访问属性。任何帮助都将不胜感激。
【问题讨论】: