我也是laravel的新手。我有一个关于Eloquent的问题:
表格结构:
<div id="test">
<div>
SOME TEXT SOME TEXT SOME
</div>
</div>
(因为我想制作&#39;喜欢&#39;表也可扩展用于评论。)
模型\ Likes.php
User: id, username
Posts: id, user_id, content
Likes: id, likeable_type, likeable_id, user_id
模型\ post.php中
class Likes extends Model
public function likeable()
{
return $this->morphTo();
}
当我打电话
class Posts extends Model
public function likes()
{
return $this->morphMany("\App\Models\Likes","likeable");
}
在我的控制器中,它会像这样返回:
$post = Posts::find($id)->likes()->get();
但我怎样才能得到这样的结果:
"likes": [
{
"id": 1,
"likeable_type": "App\\Models\\Posts",
"likeable_id": 1,
"user_id": 1,
},
{
"id": 2,
"likeable_type": "App\\Models\\Posts",
"likeable_id": 1,
"user_id": 1,
}]
非常感谢和抱歉我的英语很差!
答案 0 :(得分:0)
我相信你需要的Likes模型
class Likes extends Model
public function user()
{
return return $this->belongsTo('App\Models\User');
}
然后它应该是:
$post = Posts::find($id)->likes()->with('user')->get();