是否可以使用纯Eloquent,在没有php循环的情况下,在select语句中为关系添加自定义列和值(如果关系存在)?我想我不知道如何更好地解释,但我会努力。。。
我当前查询的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_favoite值必须是"is_favonite":"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();
反向是我的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;
在Laravel中,要添加自定义字段,请在模型上使用appends
属性,在本例中为:
<?php
protected $appends = ['is_favorite'];
并为新属性定义一个属性访问器,在本例中为:
<?php
public function getIsFavoriteAttribute() {
return $this->favorite()
->where('user_id', '=', $this->user_id)
->exists();
}
在我的案例中,最喜欢的是一种关系:
<?php
public function favorite()
{
return $this->hasMany(''Reverse'Favorite', 'favorite_id');
}
最后,当满足以下条件时,我的favorites
滤波器被激活:
<?php
if (isset($allFilters['favorites']) and filter_var($allFilters['favorites'], FILTER_VALIDATE_BOOLEAN)) {
$Interests->has('favorite');
}
我认为这是一种更好的编写代码的方法。。。如果你知道的话,你能解释一下吗?