简体   繁体   中英

Laravel relations post has many likes

        $post = Post::where('reply_to', 0)->skip(0)->take(10)->orderBy('pid', 'desc')->get();

        return Response::json(array(
            'status' => 200,
            'posts' => $post->toArray()
        ), 200);

I am suppose to display the posts and within the posts have an array info of who has liked it.

Returning it in json.

My Post model contains

public function likes()
{
    return $this->hasMany('Like', 'pid', 'pid');
}

So my problem is I cant manage to do this format. I'm kinda lost.

JSON:

{
    status 200
    posts  pid
           uid
           content
           likes
               uid

           post 2
           likes
               uid
}

Models

Post
    pid
    uid
    content

Like
    lid (like id)
    pid (post id)
    uid (user id)

Suggestions and help is very welcome


question is how to achieve the output I was trying to get. Where I return a json format of all the posts and inside each post have an array of the likes if the post has any. Its an API.

I didn't test this..but..try:

Post Model:

public function likes(){
   $this->hasMany('Like','post_id');
}

Like Model:

public function post(){
   $this->belongsTo('Post','post_id');
}

Response:

$posts = Post::with('likes')->get();

Response::json( $posts->toJson() ); 

Try this... With the likes id only:

Post::with(array('likes'=>function($query){
   $query->select('id');
}))->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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