laravel Model 取数据 json 格式存储



 namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = 'orders';
}

这个是mode

在 控制器里 show 方法里面 取数据


 $order = $this->order->show($id);
dd(order );

表里有一个 json字段的数据

图片描述


 [{"id":4,"product_id":104,"product_price":"12.01","merchant_id":8,"product_sort":142,"product_name":"\u4ea7\u54c14","product_tag":null,"product_thumb":"","product_spec":"","product_json":"","created_at":"2015-07-07 07:46:14","updated_at":"2015-07-07 07:46:14","number":3}]

通过Eloquent\Model; 取出的这个数据是 字符串 类型的

想知道 在 Model 里面 怎么设置字段, 取出来的直接是 Merchant 类型的啊

因为每次取出来 还要 自己转一下


 $order -> goods =  collect($order->product_json);

图片描述

laravel eloquent php

玩具笨了个笨 10 years, 3 months ago

http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting

通过Accessors & Mutators

给出一个参考


 php


 class User extends Model
{
    public function getProductJsonAttribute($value)
    {
        return json_decode($value);
    }

    public function setProductJsonAttribute($value)
    {
        $this->attributes['product_json'] = json_encode($value);
    }
}

.Wings answered 10 years, 3 months ago

Your Answer