Eloquent的“select”方法在使用“with”方法时无法正常工作。
Eloquent的“select”方法在使用“with”方法时无法正常工作。
我的村庄模型;
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Village extends Model { public function positions() { return $this->belongsTo(Map::class, 'id', 'field_id'); } }
我的地图类迁移;
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(); });
我的 \"VillageController\" 类的 \"villages\" 方法;
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\" 方法只需要提到,但是列返回为空。
如果我删除 $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
admin 更改状态以发布 2023年5月23日
当您尝试为村庄位置关系急切加载
Village::with(['positions'])->get();
时,会发生3件事:
- Eloquent加载所有村庄
- Eloquent加载所有位置
- Eloquent使用field_id列将位置分配给相应的村庄对象
为了使其正常工作,获取的位置需要获取field_id列,否则Eloquent将无法将它们与其对应的Villages匹配。
当您执行
$query->select('x', 'y');
时,您仅从位置表中获取x和y列。没有获取field_id列,这就是为什么Eloquent无法使用Village对象获取它们,以及为什么您会得到null而不是位置集合。
将
$query->select('x', 'y');
替换为
$query->select('field_id', 'x', 'y');
以使您的代码按预期工作。