laravel 4渴望加载为ID列表 [英] laravel 4 Eager load as a list of ids

查看:85
本文介绍了laravel 4渴望加载为ID列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对相关模型进行热切的准备.但是,我只想获取其ID,而不是获取整个相关模型.因此,最后,我将得到以下内容:

I would like to make eager load of a related model. however, instead of getting the whole related model, i'd like to retrieve just its id. so at the end, i'll have something like the following:

{
"error": false,
"invoices": {
    "id": 5,
    "biz_id": 7,
    "doc_num": 0,
    "type": 1,
    "due_date": "0000-00-00",
    "status": null,
    "to": null,
    "**related_model**": [1,2,3,4]
}

我更希望避免循环.

更新

据我了解,没有循环我无法做到,我已经完成了以下工作:

as I understand I couldn't make it without loops, i have done the following:

        $data = array();
    //get models
    $models = IncomeDoc::with('relatedReceipts')
                        ->where('type', '!=', 2)
                        ->get()
                        ->toArray();

    foreach ($models as $model)
    {
        $model['related_receipts'] = array_pluck($model['related_receipts'], 'id');

        $data[] = $model;
    }

现在这是我的问题:有什么办法可以在模型本身中进行数据处理?该代码不干净,无法重复使用,我宁愿避免使用它.

Now here is my question: is there any way that i could do that data manipulation in the model itself? this code is not clean and can not be re-used, and i'd rather avoid it.

推荐答案

您可以使用该关系获取标识符.

You can use the relationship to get the identifiers.

  1. 自定义功能:

  1. Custom function:

public function myRelationIds()
{
    return $this->myRelation->lists('id');
}

您调用该函数并将结果添加到响应中.

You call the function and add the results to the response.

通过访问器

public function getMyRelationIdsAttribute()
{
    return $this->myRelation->lists('id');
}

现在,您可以使用 appends 属性:

Now, you can make this attribute is automatically added when the model becomes Array or JSON with appends property:

protected $appends = array('my_relation_ids');

请注意,继续渴望加载关系以防止查询过多很重要.并且鉴于该关系将继续加载,您可能希望将其隐藏并且仅包含标识符:

Note that it's important to continue eager loading relation to prevent excessive queries. And given that the relationship will continue loading, you might want to hide it and only have identifiers:

protected $hidden = array('myrelation');

这篇关于laravel 4渴望加载为ID列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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