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

}

注意!

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



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