Laravel 4.2移动枢轴数据到返回模型对象


Laravel 4.2 move pivot data into return model object

我有一个从数据返回的模型,看起来像这样,

    {
        "name" : "A test name",
        "data_due" : "2015/01/01",
        "user_id" : 1,
        "viewers": [
            {
                "id": 264,
                "email": "ainley87simon@gmail.com",
                "first_name": "",
                "last_name": "",
                "display_name": "",
                "initials": null,
                "active": null,
                "cost_visible": 0,
                "notification_frequency": "H",
                "pivot": {
                    "project_id": 667,
                    "user_id": 264,
                    "involved":1
                }
            }
       ]
 }

理想情况下,我想要返回以下内容,

        {
        "name" : "A test name",
        "data_due" : "2015/01/01",
        "user_id" : 1,
        "viewers": [
            {
                "id": 264,
                "email": "ainley87simon@gmail.com",
                "first_name": "",
                "last_name": "",
                "display_name": "",
                "initials": null,
                "active": null,
                "cost_visible": 0,
                "notification_frequency": "H",
                "involved":1,
                "pivot": {
                    "project_id": 667,
                    "user_id": 264,
                }
            }
       ]
 }

基本上,我想做的是将数据透视表中返回的相关列移动到主对象中。这是一个多对多关系在project。php模型中是这样的

public function viewers() {
   return $this->belongsToMany('User', 'project_viewer')->withPivot('involved');
}

是否可以返回每个查看器对象的一部分,而不是在透视数据中?

我认为您无法在查询结果中获得pivot数据作为相关模型字段。但在你查询之后,有一些选择。

您可以为pivot字段定义一个访问器:

在查看器模型中:

function getInvolvedAttribute() 
{
   return $this->pivot->involved;
}

你可以像这样访问它:

$user = User::with('viewers')->find(1);
foreach($user->viewers as $viewer) {
   echo $viewer->involved; // Here involved is available
}

另一个方法是在您的查询结果上运行,并将其添加到您的模型中:

$user = User::with('viewers')->find(1);
foreach($user->viewers as $viewer) {
   $viewer->involved = $viewer->pivot->involved;
}

在Laravel论坛找到了一个更好的解决方案:

<!-- language: lang-php -->
<?php
// Project model
// override by aliasing the column to involved,
// preventing it being attached to the pivot model
public function viewers()
{
    $this->belongsToMany('User', 'project_viewer')->withPivot('involved as involved');
}
// User model
// To remove the pivot data in JSON, add this to the User model:
protected $hidden = ['pivot'];
// Execution
$project->viewers->all();
// [
//   {
//     "id": 264,
//     "email": "ainley87simon@gmail.com",
//     "first_name": "",
//     "last_name": "",
//     "display_name": "",
//     "initials": null,
//     "active": null,
//     "cost_visible": 0,
//     "notification_frequency": "H",
//     "involved":1  
//   },
//   ...
// ]

我认为这个解决方案更简洁,为大多数用例删除了不必要的数据,并且只在需要时才更容易访问pivot属性。

老问题,但也许它仍然会帮助一些程序员…