雄辩的"选择"方法无法使用"with"方法

Ome*_*tak 4 php laravel eloquent laravel-5

我的村庄模型;

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Village extends Model {
    public function positions() {
        return $this->belongsTo(Map::class, 'id', 'field_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

我的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();
});
Run Code Online (Sandbox Code Playgroud)

我在"VillageController"课上的"村庄"方法;

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

    return $villages;
}
Run Code Online (Sandbox Code Playgroud)

结果;

{
  "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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

只需要提及"选择"方法,但不是列返回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"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

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

jed*_*ylo 10

当你试图急切地加载村庄的位置关系时

Village::with(['positions'])->get();
Run Code Online (Sandbox Code Playgroud)

发生了三件事:

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

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

当你这样做

$query->select('x', 'y');
Run Code Online (Sandbox Code Playgroud)

您只从位置表中获取xy列.不提取field_id列,这就是为什么Eloquent无法使用Village对象获取它们,这就是为什么你得到null而不是一组位置的原因.

更换

$query->select('x', 'y');
Run Code Online (Sandbox Code Playgroud)

$query->select('field_id', 'x', 'y');
Run Code Online (Sandbox Code Playgroud)

使您的代码按预期工作.