Home >Backend Development >PHP Tutorial >laravel Model 取数据 json 格式存储

laravel Model 取数据 json 格式存储

WBOY
WBOYOriginal
2016-06-06 20:31:122628browse

<code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = 'orders';
}
</code>

这个是mode

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

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

表里有一个 json字段的数据

laravel Model 取数据 json 格式存储

<code>[{"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}]
</code>

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

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

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

<code> $order -> goods =  collect($order->product_json);
</code>

laravel Model 取数据 json 格式存储

回复内容:

<code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = 'orders';
}
</code>

这个是mode

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

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

表里有一个 json字段的数据

laravel Model 取数据 json 格式存储

<code>[{"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}]
</code>

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

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

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

<code> $order -> goods =  collect($order->product_json);
</code>

laravel Model 取数据 json 格式存储

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

通过Accessors & Mutators

给出一个参考

<code>php</code><code>class User extends Model
{
    public function getProductJsonAttribute($value)
    {
        return json_decode($value);
    }

    public function setProductJsonAttribute($value)
    {
        $this->attributes['product_json'] = json_encode($value);
    }
}
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn