代码之家  ›  专栏  ›  技术社区  ›  Yogendrasinh

在laravel 5中,仅将一列从字符串转换为数组

  •  0
  • Yogendrasinh  · 技术社区  · 7 年前

    我有一张桌子 trend 其中我有一列 hashtags hastags 列作为数组。

    用雄辩的语言表达如下。

    $singleData = Trend::find($id);

    {
        "status": "200",
        "isError": false,
        "data": {
            "message": "Trend found.",
            "singleData": {
                "id": 1,
                "title": "first trend",
                "start_date": "2018-11-16",
                "end_date": "2018-11-16",
                "slug": "first-trend",
                "hashtags": "first,trend,second",
                "created_by": 1,
                "status": false,
                "created_at": "2018-11-16 00:00:00",
                "updated_at": "2018-11-19 08:51:20"
            }
        }
    }
    

    我希望结果如下

    {
        "status": "200",
        "isError": false,
        "data": {
            "message": "Trend found.",
            "singleData": {
                "id": 1,
                "title": "first trend",
                "start_date": "2018-11-16",
                "end_date": "2018-11-16",
                "slug": "first-trend",
                "hashtags": [
                    "first",
                    "trend",
                    "second"
                    ],
                "created_by": 1,
                "status": false,
                "created_at": "2018-11-16 00:00:00",
                "updated_at": "2018-11-19 08:51:20"
            }
        }
    }
    

    我在我的工作中使用了下面的代码,得到了这个结果 TrendController .

    $singleData->hashtags = explode(',', $singleData->hashtags);

    但如果可能的话,我希望有更好的方法用雄辩的口才来获取信息。

    1 回复  |  直到 7 年前
        1
  •  1
  •   wau    7 年前

    你可以用 Mutators 为了它

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Trend extends Model
    {
        /**
         * Get the trend's hashtag.
         *
         * @param  string  $value
         * @return string
         */
        public function getHashtagttribute($value)
        {
            return explode(',', $value);
        }
    }
    

    现在它将像这样工作:

    $trend->hashtag; // array
    

    或者,如果您将其用于API,则可以使用 Eloquent: API Resources

    您可以使用artisan命令:php artisan make:resource Trend--collection

    <?php
    
    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class User extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'hashtags' => explode(',', $singleData->hashtags),
            ];
      }
    }
    

    use App\User;
    use App\Http\Resources\Trend as TrendResource;
    
    Route::get('/trend', function () {
        return new TrendResource(Trend::find(1));
    });
    
    推荐文章