我有以下内容查询container_slots
表并返回所有剩余的未占用的插槽。
return DB::table('container_slots')
->where('occupied', false)
->join('plate_containers','container_slots.plate_container_id', '=', 'plate_containers.id')
->select('plate_containers.name AS Container', DB::raw('count(container_slots.slot) as no_of_slots'))
->groupBy('plate_container_id')->get();
这很好用。
返回
[
{
"Container": "Test container #1",
"no_of_slots": 3
}
]
我想要实现的是将其与用户访问页面时调用的index()方法结合起来。
public function index()
{
$plateContainers = PlateContainer::paginate(25);
return response()->success($plateContainers);
}
返回此信息。
{
"success": {
"total": 2,
"per_page": 25,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 51,
"name": "Test container #1",
"description": null,
"number_of_slots": 5,
"material": "Glass",
"comment": null,
"plate_container_type_id": 51,
"storage_location_id": 13,
"equipment_status_code_id": 17,
"created_by": 1,
"created_at": "2016-12-30 10:24:08",
"updated_at": "2017-01-04 15:43:05",
"updated_by": 1
},
{
"id": 52,
"name": "Test container #2",
"description": null,
"number_of_slots": null,
"material": "glass",
"comment": null,
"plate_container_type_id": 51,
"storage_location_id": 7,
"equipment_status_code_id": 17,
"created_by": 1,
"created_at": "2017-01-04 09:29:15",
"updated_at": "2017-01-04 09:38:51",
"updated_by": 1
}
]
}
}
在data
数组中的某个地方,我希望获得上述查询的键和值(对于每个对象)。这可能吗?
我试图实现这一点,急切的加载,但无法做到正确。
更多信息。
PlateContainer 模型
public function containerSlots()
{
return $this->hasMany('App\Models\ContainerSlot');
}
ContainerSlot 模型
public function plateContainer()
{
return $this->belongsTo('App\Models\PlateContainer');
}
希望你明白了。谢谢你的时间。
更新#1 :根据以下答案。
我尝试了一下建议的方法,这就是它返回的内容。
"data": [
{
"id": 51,
"name": "Test container #1",
"description": null,
"number_of_slots": 5,
"material": "Glass",
"comment": null,
"plate_container_type_id": 51,
"storage_location_id": 13,
"equipment_status_code_id": 17,
"created_by": 1,
"created_at": "2016-12-30 10:24:08",
"updated_at": "2017-01-04 15:43:05",
"updated_by": 1,
"my_count": [
{
"Container": "Test container #1",
"no_of_slots": 4
},
{
"Container": "Test container #3",
"no_of_slots": 3
}
],
几乎就在那里。只有这会返回每个PlateContainer
实例的所有未占用的插槽。我们的想法是仅特定plate container
的未占用广告位。所以在这种情况下我只需要Test Container #1
未占用的插槽。 Test Container #3
应该是下一个实例。那有意义吗?
答案 0 :(得分:0)
急切加载应该可以正常工作。
$plateContainers = PlateContainer::with('ContainerSlot')->paginate(25);
这会将ContainerSlots属性附加到每个PlateContainer中。
如果你只想在每个PlateContainer模型中都有这个计数查询,你可以使用mutators:
https://laravel.com/docs/5.3/eloquent-mutators
我们的想法是将$ appends属性设置到您的模型中并定义自定义属性getter:
$appends = ['my_count'];
public function getMyCountAttribute()
{
return; //return your DB query here
}
如果你只想在那个索引动作中计数,也许你应该只返回你的查询而不是PlateContainer :: paginate();
希望这有帮助,如果没有,请随时发表评论!