【发布时间】:2015-05-22 03:25:43
【问题描述】:
是否有可能使用纯 Eloquent 使用,没有 php 循环,在选择语句中添加一个自定义列和值到一个关系,如果关系存在的话?我认为我不知道如何更好地解释,但我会尝试......
我当前查询的 json 结果(雄辩)是以下 json:
[
{
"id": 5,
"user_id": 3,
"category_id": 2,
"city_id": 1,
"title": "Outro teste",
"body": "999999 sdf23asd f23asd32f1 as321f32as1d f1sdf",
"image_path": "",
"status": "ACTIVE",
"expires_at": "2015-03-20 04:44:53",
"popularity": 0,
"is_favorite": "true",
"category": {
"id": 2,
"name": "Categoria 2",
"status": "ACTIVE",
"color": "#0F0",
"parent_id": null,
"type": "INTEREST",
"slug": "categoria-2",
"icon_path": null
},
"favorite": []
},
{
"id": 4,
"user_id": 3,
"category_id": 3,
"city_id": 1,
"title": "Interesse de Teste 2",
"body": "2321fads132f123d sf 12sdf sd132",
"image_path": "",
"status": "ACTIVE",
"expires_at": "2015-03-21 02:34:53",
"popularity": 0,
"is_favorite": "true",
"category": {
"id": 3,
"name": "Subcategoria 1",
"status": "ACTIVE",
"color": "#00F",
"parent_id": 1,
"type": "INTEREST",
"slug": "subcategoria-1",
"icon_path": null
},
"favorite": [
{
"id": 1,
"user_id": 3,
"favorite_id": 4,
"type": "INTEREST",
"created_at": null,
"updated_at": null
}
]
}
]
在结果is_favorite 的第一个索引中,字段值必须是“is_favorite”:“false”,因为不是exists() 的favorite 关系,并且在第二个索引中,is_favorite 值必须是“is_favorite”:“true”因为存在关系。
我的代码来获取这个当前的 json 结果我认为这可以更好......我在 Laravel 5.0 中是菜鸟:
<?php
$Interests = \Reverse\Interest::with('category')
->where('status', '<>', 'DELETED')
->take($limit)
->offset($offset);
if (isset($allFilters['user'])) {
$Interests->where('user_id', $allFilters['user']);
}
if (isset($allFilters['popularity'])) {
$Interests->orderBy('popularity', 'desc')
->orderBy('expires_at', 'asc');
}
if (isset($allFilters['favorites'])) {
if($Interests->with('favorite')->exists()) {
$Interests->select(DB::raw('*, "true" AS is_favorite'));
}
}
$responseContent = $Interests->get();
Reverse 是我的 API 命名空间。 json 返回是使用在响应头上传递的 application/json 进行的:
<?php
// My Json Response Example
$Response = new \Illuminate\Http\Response();
$Response->header('Content-Type', 'application/json');
$Response->setContent($Interests->get());
return $Response;
【问题讨论】:
标签: php mysql api laravel eloquent