有说服力的“选择”;方法不能使用"with"方法


Eloquent "select" method not working with using "with" method

My Village模型;

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Village extends Model {
    public function positions() {
        return $this->belongsTo(Map::class, 'id', 'field_id');
    }
}

My Map类迁移;

Schema::create('map_data', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('field_type');
    $table->integer('field_id');
    $table->string('x');
    $table->string('y');
    $table->timestamps();
});

我的"villages"方法在" villagcontroller "类上;

public function villages() {
    $villages = Village::with([
        'positions' => function ($query) {
            $query->select('x', 'y');
        }
    ])->get();
    return $villages;
}

结果;

{
  "villages": [
    {
      "id": 1,
      "name": "village 1",
      "created_at": "2016-10-26 18:36:34",
      "updated_at": "2016-10-26 18:36:34",
      "positions": null
    },
    {
      "id": 2,
      "name": "village 2",
      "created_at": "2016-10-26 18:36:34",
      "updated_at": "2016-10-26 18:36:34",
      "positions": null
    }
  ]
}

只需要提到"Select"方法,而不需要提到列返回NULL。

如果我删除$query->select('x', 'y');代码,返回以下结果:

{
  "villages": [
    {
      "id": 1,
      "name": "village 1",
      "created_at": "2016-10-26 18:36:34",
      "updated_at": "2016-10-26 18:36:34",
      "positions": {
        "id": 1,
        "field_type": "1",
        "field_id": "1",
        "x": "21",
        "y": "21",
        "created_at": "2016-10-26 18:36:34",
        "updated_at": "2016-10-26 18:36:34"
      }
    },
    {
      "id": 2,
      "name": "village 2",
      "created_at": "2016-10-26 18:36:34",
      "updated_at": "2016-10-26 18:36:34",
      "positions": {
        "id": 2,
        "field_type": "1",
        "field_id": "2",
        "x": "0",
        "y": "0",
        "created_at": "2016-10-26 18:36:34",
        "updated_at": "2016-10-26 18:36:34"
      }
    }
  ]
}

但是我使用$query->select('x');代码,结果应该是以下

资源:https://stackoverflow.com/a/32185643/3287225

当您尝试急切加载位置关系

村庄时
Village::with(['positions'])->get();

发生了三件事:

  1. Eloquent加载所有村庄
  2. Eloquent加载所有位置
  3. Eloquent使用field_id列为相应的Village对象分配位置

为了使它工作,获取的位置需要有field_id列被获取,否则Eloquent无法将它们与相应的村庄匹配。

当你这样做

$query->select('x', 'y');

你只从你的位置表中获取xy列。field_id列没有被获取,这就是为什么Eloquent无法用Village对象获取它们,这就是为什么你得到null而不是位置的集合。

代替

$query->select('x', 'y');

$query->select('field_id', 'x', 'y');

相关文章: