如何获得我喜欢的用户列表和他们的信息


How to get list of users I have favourited and their information

我正在Laravel 5中构建一个API,并希望获得我喜欢的人和他们的信息列表。

用户模型
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['username', 'email', 'password'];
/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'password',    
    'secret_key'
];
public function attribute()
{
    return $this->hasOne('App'UserAttributes', 'user_id', 'id');
}
public function photos()
{
    return $this->hasMany('App'Photos', 'user_id', 'id');
}
public function favourites()
{
    return $this->hasMany('App'Favourites', 'from', 'id');
}
public function favourited()
{
    return $this->hasMany('App'Favourites', 'to', 'id');
}

收藏模型
class Favourites extends Model {
   protected $table = 'favourite';
   public function user()
   {
       return $this->belongsTo('App'User', 'from', 'id');
    }
}

用户属性模型

class UserAttributes extends Model {
    protected $table = 'user_attributes';
    public function user()
    {
       return $this->belongsTo('User', 'user_id', 'id');
    }
}
  • 用户表包含用户名,电子邮件密码等信息
  • 属性表保存像高度,重量等信息(这是为了使用户的表没有70列)
  • 最爱表保存来自和到列。From是我的用户id, to是我喜欢的用户id。

这是我目前拥有的:

return User::with(['attribute','favourites'])->find($user_id);

我想达到的效果如下:

"favourites": [
    {
        "id": "15",
        "from": "231", // My ID
        "to": "**100**", // ID of user I have favourited (FK)
        "created_date": "2013-04-10 21:35:28",
        "user": [
            "id": "**100**", // USER ID
            "username": "someuser",
            "email": "random@mail.com",
            "email_verified": "1",
            "has_photo": "1",
            "dob": "1952-11-12"
        ],
        "attribute": [
            "id": "105",
            "user_id": "**100**", // USER ID (FK)
            "height": "70",
            "car": "0",
            "pet": "2",
        ]
    }
]

我需要我的json像上面这样,当我调用api URL/api/v1/favorites ?My_id =231在我的应用程序或网站,并获得所有必要的信息,而不是单独加载它。除非我说错了?

如果你认为这样做是错误的应用程序,我将非常高兴听到你的意见,因为这对我来说是新的东西。

您当然需要在发送数据之前对其进行转换。你可能想要创建一个函数或一个类UserTransformer来帮你做这件事。分形可能会对你有所帮助。如果您是laravast的粉丝或Laravel的新手,您肯定错过了增量API系列(https://laracasts.com/series/incremental-api-development)。