使用elequent构建器查询Laravel模型中的Json属性字段

时间:2017-10-29 09:23:13

标签: json laravel

我想用elequent builder过滤数据库中的json字段(post)。

我需要帮助查询elequent。

attributes: array:17 [▼
    "id" => 2
    "admin_id" => 0
    "email" => "jafari1989@gmail.com"
    "fullname" => "asdasdasd"
    "subject" => "asdasdasdasd"
    "desc" => """
      sadasd\r\n
      """
    "cell_phone" => "09124251131"
    **"post" => "{"modir": 0, "saken": 0, "ozv_modir": 0}"**
    "elevator_spec" => null
    "type" => null
    "control" => null
    "count_stop" => null
    "door_type" => null
    "lift_capacity" => null
    "insurance" => null
    "created_at" => "2017-10-28 21:24:54"
    "updated_at" => "2017-10-28 21:24:54"
  ]

2 个答案:

答案 0 :(得分:3)

You should use setter and getter in the model in case of that specific field that you want .

     public function setPostAttribute($value)
    {
        $this->attributes['post'] = json_encode($value, JSON_UNESCAPED_UNICODE);
    }

   public function getPostAttribute()
    {
        $model = new $this;
        $jsonToConvert = $this->attributes['post'];
        $modelArray = $model->fromJson($jsonToConvert);

        return $model->newInstance($modelArray);
    }


after that in your controller :

    Orders::where('post->modir', 0)->get(

答案 1 :(得分:0)

Laravel为您提供了一种简单的方法,使用Array & JSON Casting

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'post' => 'array',
    ];
}

定义了广告素材后,您可以访问options属性,它会自动从JSON反序列化为PHP array。设置options属性的值时,给定的数组将自动序列化为JSON以进行存储:

$user->post = ['modir' => 'blabla'];
$user->save();