在急切加载时,仅选择相关模型中的某些列

时间:2014-07-17 10:53:33

标签: laravel laravel-4 eloquent

我有两个相关的模型:

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"
 }]
}]

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

3 个答案:

答案 0 :(得分:2)

一个看似这样的雄辩方法怎么样?

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

$array_columns可以是表示所需列的字符串或字符串数​​组吗?

答案 1 :(得分:2)

使用select()laravel方法:

<script>

function TheLogin() {

if (this.document.login.pass.value == 'password1') {
  top.location.href="pageno1.php";
}
else if (this.document.login.pass.value == 'password2') {
  top.location.href="pageno2.php";
}
else {
  window.alert("Incorrect password, please try again.");
  }
}

</script>

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

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

答案 2 :(得分:1)

如果您希望始终仅返回类别关系中的特定字段,则定义关系中的选择将起作用,但如果您希望即时执行某个特定查询,你可以告诉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('sttributes.id', 'attributes.name', 'categories.id', 'categories.name', 'categories.attribute_id')
            ->get();