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


Filtering column with json data using Eloquent ORM included with Laravel

我正在制作一个数据过滤器,我需要过滤包含 json 保存数据的列。表结构如下所示:

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

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

使用 getter get<Column>Attribute

class YourModel extends Eloquent {
    public function getTagsAttribute($value)
    {
        return json_decode($value);
    }
}
您可以使用

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

下面是返回模型集合的示例:

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();
    }
}