我的村庄模特;
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Village extends Model {
public function positions() {
return $this->belongsTo(Map::class, 'id', 'field_id');
}
}
我的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();
});
我的&#34;村庄&#34;问题&#34; VillageController&#34;类;
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
}
]
}
&#34;选择&#34;方法只需要提及,但不是列返回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');
代码,结果应该是以下
答案 0 :(得分:7)
当您尝试用
急切加载村庄的位置关系时Village::with(['positions'])->get();
发生了三件事:
为了使其起作用,获取的位置需要获取 field_id 列,否则Eloquent无法将它们与相应的村庄匹配。
当你这样做时
$query->select('x', 'y');
您只从位置表中获取 x 和 y 列。 field_id 列未被提取,这就是为什么Eloquent无法使用 Village 对象获取它们的原因以及这就是为什么你 > null 而不是位置集合。
替换
$query->select('x', 'y');
与
$query->select('field_id', 'x', 'y');
使您的代码按预期工作。