【问题标题】:Filtering column with json data using Eloquent ORM included with Laravel使用 Laravel 附带的 Eloquent ORM 过滤包含 json 数据的列
【发布时间】:2015-02-02 17:49:50
【问题描述】:

我正在制作一个数据过滤器,我需要过滤一个包含 json 保存数据的列。表结构类似这样:

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

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

【问题讨论】:

    标签: php json laravel eloquent


    【解决方案1】:

    使用getter get<Column>Attribute:

    class YourModel extends Eloquent {
    
        public function getTagsAttribute($value)
        {
            return json_decode($value);
        }
    
    }
    

    【讨论】:

    • 那么我该如何使用 Article::where('tags', '=', $tags) ?
    • 您可以创建一个类似于我为您创建的范围:laravel.io/bin/0eElj#
    • 注意,如果表很大,$q->whereOr('tags', 'like', '%"'.$tag.'"%'); 会很慢,如果有很多次相同的标签,带有标签的 json 会很重。为了可扩展性和优化,最好创建一个标签模型和一个关系 YourModel Tag,因此您将首先获得 Tag::whereIn('name', $tags) 然后在关联表和 YourModel 对象或等效连接中从中获取 YourModel id .处理大量数据时速度会非常快。
    • @KyleK 你能给我举个例子吗?
    【解决方案2】:

    您可以使用 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);
      }
    }
    

    【讨论】:

      【解决方案3】:
      class YourModel extends Eloquent {
      
          public function getTagsAttribute($value)
          {
              parent::where($value)->get();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        • 2013-05-15
        • 2021-11-18
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2017-10-17
        相关资源
        最近更新 更多