【问题标题】:Get result by joining with JSON Object Key of a column通过加入列的 JSON 对象键获取结果
【发布时间】:2021-03-07 04:55:01
【问题描述】:

points 表 - 列:id、json_column

[
 {"user_id":"1","points":"1"},
 {"user_id":"2","points":"1"},
 {"user_id":"3","points":"0"},
]

users 表 - 列:id、name

1 | steve
2 | matthew
3 | john

预期结果。所有使用 eloquent 获得积分的用户

1-steve-1
2-matthew-1
3-john-0

$users=User::all();

是否可以使用 with 语句获取输出

编辑:

点模型

protected $casts = [
        'json_column' => 'json'
 ];

用户模型

 public function point()
{
    return $this->hasOne(Point::class, 'json_column->user_id', 'id');
}

打印的查询 - 但它返回 null:

select * 
from `points` 
where json_unquote(json_extract(`points`.`json_column`, '$."user_id"')) in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)

如果单个 json 数组在列中,则此方法有效:

{"user_id":"1","points":"1"}

如果它包含数组数组,则代码不起作用

[
 {"user_id":"1","points":"1"},
 {"user_id":"2","points":"1"},
 {"user_id":"3","points":"0"},
]

编辑 2: 转换为数组。但不工作

 protected $casts = [
        'application_data' => 'array'
    ];

【问题讨论】:

  • 是的。可以根据您的查询

标签: laravel eloquent lumen


【解决方案1】:

是的,假设您已经创建了 UserPoint 模型:

用户模式

class User extends Model
{
    protected $table = 'users';

    protected $guarded = [];


    public function point()
    {
        return $this->hasOne(Point::class, 'json_column->user_id');
    }
}

点模式

class Point extends Model
{
    protected $table = 'points';

    protected $guarded = [];
    protected $casts = [
        'json_column' => 'json'
    ];

}

然后您可以使用 with 预加载用户点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-05
    • 2017-06-03
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多