【问题标题】:Select only certain columns in related model when eager loading急切加载时仅选择相关模型中的某些列
【发布时间】:2014-09-08 05:05:57
【问题描述】:

我有两个相关的模型:

class Attribute extends Eloquent
{
    public function categories()
    {
        return $this->hasMany('Category');
    }
}

class Category extends Eloquent
{
    public function attributes()
    {
        return $this->belongsTo('Attribute');
    }
}

我想将所有属性及其类别作为 JSON 对象返回,但我只想选择两个模型中的某些字段(即不返回 JSON 中的“created_at”之类的字段)。

我试过了:

$attributes = Attribute::select('id', 'name')
 ->with(['categories' => function ($query) {
   $query->select('categories.id', 'categories.name', 'categories.attribute_id');
 }]);

Response::JSON($attributes->get());

但是尽管对相关模型进行了选择查询,但仍会返回未请求的字段:

attributes: [{
 id: 3,
 name: "Organisation",
 categories: [{
  id: 3,
  name: "Asia HQ",
  attribute_id: 3,
  created_at: "2013-11-30 00:00:00",
  updated_at: "2013-11-30 00:00:00"
 }]
}]

如何在预加载时只选择相关模型中的某些列?

【问题讨论】:

  • 类似的事情在stackoverflow.com/questions/14727038/…解决了
  • 检查执行了什么查询,因为对于hasMany,它按预期工作。
  • @delmadord 我知道我可以在模型中设置 $hidden 和 $visible 。但是我需要在不同的页面上显示不同的字段,所以我想要一个动态的解决方案。
  • @MMacdonald 你应该检查变压器——这就是你需要的。再一次 - 您粘贴的代码按预期工作(L4.2),所以要么是 belongsToMany 关系,这是错误的,要么你错过了一些东西。

标签: laravel laravel-4 eloquent


【解决方案1】:

像这样的雄辩的方法呢?

public function dynamicAttributes($array_columns) {
  return $this->belongs_to('User')->select((array) $array_comuns);
}

$array_columns 可以是代表您想要的列的字符串或字符串数​​组?

【讨论】:

    【解决方案2】:

    利用 select() laravel 方法:

    $attributes = Attribute::select('id', 'name')->with(['categories' =>function($query){
            $query->select(['categories.id', 'categories.name','categories.attribute_id'])->get();
    }]);
    
    Response::JSON($attributes->get());
    

    要使 select 方法在预加载中工作,您需要将 foreign_key 包含在 选定的列列表。

    参考http://laravel-tricks.com/tricks/column-selection-in-eager-loading

    【讨论】:

      【解决方案3】:

      如果您想始终从类别关系中返回那些特定字段,则在关系中定义选择将起作用,但如果您想为一个特定查询即时执行此操作,请询问Eloquent 只返回那些字段。

      $attributes = Attribute::with(['categories' => function ($query) {
         $query->select('id', 'name', 'attribute_id');
       }])->get('id', 'name');
      

      ... 或者你可以使用 Fluent

      DB::table('attributes')
                  ->join('categories', 'attributes.id', '=', 'categories.attribute_id')
                  ->select('attributes.id', 'attributes.name', 'categories.id', 'categories.name', 'categories.attribute_id')
                  ->get();
      

      【讨论】:

        猜你喜欢
        • 2014-10-31
        • 2013-06-10
        • 2020-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多