使用Laravel附带的Eloquent ORM过滤带有json数据的列

[英]Filtering column with json data using Eloquent ORM included with Laravel


I'm making a data filter and I need to filter a column with json saved data. The table structure is similar to this:

我正在制作数据过滤器,我需要使用json保存的数据过滤列。表结构与此类似:

____________________________________
| id | name    | tags              |
|____|_________|___________________|
| 1  | example | ["3","4","5","6"] |
|____|_________|___________________|

Any idea how to filter this column by tags using Eloquent ORM included with Laravel?

知道如何使用Laravel附带的Eloquent ORM按标签过滤此列吗?

3 个解决方案

#1


1  

Use the getter get<Column>Attribute:

使用getter get 属性:

class YourModel extends Eloquent {

    public function getTagsAttribute($value)
    {
        return json_decode($value);
    }

}

#2


0  

You could use mySql JSON_CONTAINS function since it is optimized on the DB level. Unfortunately Eloquent doesn't (?) provide wrappers for functions like this so you can fall back to plain SQL and create your models from the results.

您可以使用mySql JSON_CONTAINS函数,因为它在数据库级别进行了优化。不幸的是,Eloquent没有(?)为这样的函数提供包装器,因此您可以回退到纯SQL并根据结果创建模型。

This is an example that returns a Collection of Models:

这是一个返回模型集合的示例:

class myModel extends Eloquent {

  protected   $casts = [
      'json_column' => 'array', // this is JSON type in the DB
  ];

  /**
  * Returns a Collection of 'myModel' that have $search value
  * stored in the 'json_column' array
  *
  * @param  string $search
  * @return \Illuminate\Database\Eloquent\Collection
  */
  public static function findInJsonColumn($search){
    $data = \DB::select("SELECT * FROM table_name WHERE JSON_CONTAINS(json_column, '[\"$search\"]')");
    return self::hydrate($data);
  }
}

#3


0  

class YourModel extends Eloquent {

    public function getTagsAttribute($value)
    {
        parent::where($value)->get();
    }

}
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/02/02/7207386bc77ec295c93403516b1397dc.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告