【问题标题】:Laravel: how to set a custom column with conditions?Laravel:如何设置带有条件的自定义列?
【发布时间】: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


    【解决方案1】:

    在 Laravel 中添加自定义字段,在您的模型上使用 appendsattribute,在这种情况下:

    <?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');
    }
    

    我认为存在编写此代码的更好方法...如果您知道,您能解释一下吗?

    【讨论】:

    • 您定义了一个新的附加属性,但从不使用它。在过滤中,您仍然调用原始关系,因此(在当前代码中)添加附加属性是没有附加值的。对吗?
    • @Luceos 是的,还有一个附加值:在我的结果中现在有一个is_favorite: truefalse。而这正是我所需要的。原始关系只是从与favorite 有关系的给定user 中获取结果。是否有更好的方法来编写此代码?
    猜你喜欢
    • 2017-01-08
    • 2015-11-29
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多