使用 Laravel 附带的 Eloquent ORM 过滤包含 json 数据的列
Filtering column with json data using Eloquent ORM included with Laravel
我正在制作数据过滤器,我需要用 json 保存的数据过滤列。 table结构类似这样:
____________________________________
| id | name | tags |
|____|_________|___________________|
| 1 | example | ["3","4","5","6"] |
|____|_________|___________________|
知道如何使用 Laravel 中包含的 Eloquent ORM 按标签过滤此列吗?
使用 getter get<Column>Attribute
:
class YourModel extends Eloquent {
public function getTagsAttribute($value)
{
return json_decode($value);
}
}
您可以使用 mySql JSON_CONTAINS 函数,因为它在数据库级别进行了优化。不幸的是 Eloquent 不(?)为这样的函数提供包装器,因此您可以回退到普通 SQL 并根据结果创建模型。
这是一个 returns 模型集合的示例:
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();
}
}
我正在制作数据过滤器,我需要用 json 保存的数据过滤列。 table结构类似这样:
____________________________________
| id | name | tags |
|____|_________|___________________|
| 1 | example | ["3","4","5","6"] |
|____|_________|___________________|
知道如何使用 Laravel 中包含的 Eloquent ORM 按标签过滤此列吗?
使用 getter get<Column>Attribute
:
class YourModel extends Eloquent {
public function getTagsAttribute($value)
{
return json_decode($value);
}
}
您可以使用 mySql JSON_CONTAINS 函数,因为它在数据库级别进行了优化。不幸的是 Eloquent 不(?)为这样的函数提供包装器,因此您可以回退到普通 SQL 并根据结果创建模型。
这是一个 returns 模型集合的示例:
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();
}
}