Laravel 4.1从响应中删除数据透视属性

has*_*b32 15 laravel-4

我正在使用laravel 4.1构建一个api.我有一个工作正常的表.但响应来自我不想要的枢轴属性.正如您将在我的示例中看到的,我必须有两个表名:trip和users.我不希望在响应中看到数据透视表属性.这是一个例子:

[
    {
        "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
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的用户模型:

public function trips(){
        return $this->belongsToMany('Trip');
    }
Run Code Online (Sandbox Code Playgroud)

这是我的旅行模型:

public function users(){
        return $this->belongsToMany('User');
    }
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

public function index($tripId)
    {
        $userCollection = Trip::find($tripId)->users;
        return $userCollection;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的路线:

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

有什么方法我可以使用laravel删除枢轴属性或我必须使用PHP?

小智 32

使用$hidden模型的属性,您可以向其添加属性或关系,并且数据透视表基本上充当关系.

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

    public function bars()
    {
        return $this->belongsToMany('Bar');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @TLGreg如何只隐藏关键的特定字段?说,我的关键字中有'a_id`,`b_id`和`dummy`字段,我想从三个中只检索`dummy`.那有什么办法吗? (3认同)