首页 文章

Laravel JSON对Eloquent的回应

提问于
浏览
0

我有三个表,称为线程,帖子,用户

线程得到了

id
title
etc.

帖子得到了

id
thread_id
user_id
post
post_date
etc.

用户得到了

id
username 
password
email
etc.

当用户想要查看线程时,我只需使用post数据调用jquery ajax请求来发送线程id并返回此代码:

Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get());

这段代码完美地完成了他的工作,并通过相同的thread_id返回帖子 . (帖子模型也渴望通过查看user_id来加载用户) .

但是这段代码 grab 了帖子和用户的每个属性,我的意思是json,post_date,post_updatereason,user_password,user_email表格中的所有列 .

我只想用json抓取post,username和post_date

2 回答

  • 1

    您可以将 public static $hidden = array('list', 'of', 'fields'); 添加到扩展Eloquent的模型中 . 然后,将返回您在数组中创建的字段 . 有关更多信息refer to the documentation .

    例如

    class User extends Eloquent {
      public static $hidden = array('password', 'email');
    }
    

    将返回没有 passwordemail 的用户模型 .

  • 4

    如果您使用的是laravel 3,并且版本4可能相同,那么您应该能够使用get方法指定所需的列 .

    Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get(['username','post_date']));
    

相关问题