Laravel 4.1从响应中删除数据透视表属性 [英] Laravel 4.1 remove pivot attributes from response

查看:68
本文介绍了Laravel 4.1从响应中删除数据透视表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel 4.1来构建一个api.我有一个枢轴工作良好的表.但是响应带有我不想要的数据透视属性.正如您将在我的示例中看到的那样,我必须有两个表名称:旅行和用户.我不想在响应中看到数据透视表属性.这是示例:

I am using laravel 4.1 to build an api. I have pivot a table which is working fine. But the response comes with pivot attributes which i don't want. as you will see in my example i have to two tables name: trips and users. I don't want to see pivot table attributes in my response. Here is the example:

[
    {
        "id": 140,
        "name_first": "hasan",
        "name_last": "hasibul",
        "profile_image": "/assets/images/default-profile-img.png",
        "created_at": "2013-09-18 08:19:50",
        "last_login": "2013-12-26 11:28:44",
        "status": "active",
        "last_update": "2013-10-15 13:40:47",
        "google_refresh_token": null,
        "is_admin": 1,
        "updated_at": null,
        "pivot": {
            "trip_id": 200,
            "user_id": 140
        }
    }

这是我的用户模型:

public function trips(){
        return $this->belongsToMany('Trip');
    }

这是我的旅行模型:

public function users(){
        return $this->belongsToMany('User');
    }

这是我的控制者:

public function index($tripId)
    {
        $userCollection = Trip::find($tripId)->users;
        return $userCollection;
    }

这是我的路线:

//get all the users belongs to the trip
Route::get('trips/{tripId}/users', array(
    'as' => 'trips/users/index',
    'uses' => 'TripUserController@index'
));

有什么方法可以使用laravel删除数据透视表属性,或者我必须使用php吗?

is there any way i can remove pivot attributes using laravel or i have to use php ?

推荐答案

使用模型的$hidden属性,可以向其添加属性或关系,而数据透视表基本上是一种关系.

Use the $hidden property of the model, you can add attributes or relations to it and the pivot is basicly acts as a relation.

class Foo extends Eloquent
{
    protected $hidden = array('pivot');

    public function bars()
    {
        return $this->belongsToMany('Bar');
    }
}

这篇关于Laravel 4.1从响应中删除数据透视表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆