在laravel 4中,使用eloquent可以在父模型对象中包含数据透视表字段


In laravel 4, using eloquent, is there a tidy way to include a pivot table field in the parent model's object?

目前,模型jsonify如下:

"event": 
{
    "id": 3,
    "guid": "17fca759-e0b0-0692-0153-30125231b135",
    ~~snip~~
    "pivot": {
        "company_id": 1,
        "event_id": 3,
        "job_number": "31310"
    }
}

我想有一些方法可以轻松地将job_number字段移动到主event对象中,以便它返回平面。

我们可以绕过它,但是稍微清理一下返回对象会非常groovy。前端不需要知道这种关系类型,他们只需要知道在给定的上下文中,工作编号是什么。

附录

另一种(和一个很长的镜头),是否有一种方法让模型访问自己的数据透视表?(使用mutator)

<<p> 解决方案/strong> 在delmadord的帮助下,最终输出如下所示:
"events":
{
    "id": 3,
    "guid": "17fca759-e0b0-0692-0153-30125231b135",
    ~~snip~~
    "job_number": "31310"
},

通过创建一个返回$this->relations['pivot']->job_number的突变子getJobNumberAttribute(),设置$appends = ['job_number']$hidden = ['pivot']来清理响应对象。对结果非常满意。

array_dot()帮助函数对于第一个问题可能很方便。将在之后使用with()load()函数进行即时加载。

另外,从文档中,可以访问模型的数据透视表:

$user = User::find(1);
foreach ($user->roles as $role)
{
    echo $role->pivot->created_at;
}

您应该能够以相同的方式从模型内部访问作为$this->relation->pivot的数据透视表,假设数据透视表已经迁移并且belongsToMany()关系正常工作。

编辑

似乎在模型中访问pivot模型是由$this->relations['pivot']->property

完成的。

您可以使用accessor +追加或简单的select:

$model = Model::with(['events' => function ($q) {
   $q->select('YOUR_PIVOT_TABLE.job_number');
}])->first();
// then it's accessible as ordinary properties:
$model->events->first()->toJson();
"event": 
{
    "job_number": "31310",
    "id": 3,
    "guid": "17fca759-e0b0-0692-0153-30125231b135",
    ~~snip~~
    "pivot": {
        "company_id": 1,
        "event_id": 3,
        "job_number": "31310"
    }
}

Accessor的工作原理与前面提到的类似,但您需要检查它是否在关系上下文中(即pivot存在):

// Event model
public function getJobNumberAttribute()
{
   return (count($this->pivot)) ? $this->pivot->job_number : null;
}