我正在使用 laravel 4.1 构建 api。我有一个工作正常的枢轴表。但响应带有我不想要的枢轴属性。正如您将在我的示例中看到的,我有两个表名称:trips 和 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
}
}
这是我的用户模型:
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 吗?
使用模型的
$hidden
属性,您可以向其添加属性或关系,并且枢轴基本上充当关系。
class Foo extends Eloquent
{
protected $hidden = array('pivot');
public function bars()
{
return $this->belongsToMany('Bar');
}
}
如果您只想从响应中删除任何一列,那么您可以尝试如下操作:
在您的模型中:
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
unset($attributes['pivot']['user_id']);
return $attributes;
}
这样您将只获得所需的属性。
您可以将其添加到“隐藏”数组中。在型号页面
protected $hidden = [
'pivot'
];
如上所述,您可以通过将以下内容添加到相关模型来从响应中删除数据透视属性。
protected $hidden = [
'pivot'
];
此外,如果您想从数据透视表中选择特定字段以显示在相关用户对象中,您可以使用 Laravel 5.8 将其添加到控制器中。当您使用上面的代码片段隐藏枢轴信息时,这也适用。
public function index(Trip $trip)
{
return $trip->users()->select(['trip_id'])->paginate();
}
您将收到一些对象,其中 trip_id 添加到用户对象中。
{
"data": [
{
"id": 140,
"trip_id": 200,
"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
}
}
]
}