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

laravel Model 取数据 json 格式存储

WBOY
Release: 2016-06-06 20:31:12
Original
2632 people have browsed it

<code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;

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

这个是mode

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

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

表里有一个 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>
Copy after login
Copy after login

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

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

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

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

laravel Model 取数据 json 格式存储

回复内容:

<code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;

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

这个是mode

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

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

表里有一个 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>
Copy after login
Copy after login

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

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

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

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

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template