简体   繁体   中英

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:

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

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

Use the getter get<Column>Attribute :

class YourModel extends Eloquent {

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

}

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.

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);
  }
}
class YourModel extends Eloquent {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM