【问题标题】:Find the value in where in json clause在 json 子句的 where 中查找值
【发布时间】:2020-09-18 05:43:33
【问题描述】:

我有coupons 表,其中我有rules 列这是json

rules:"{\"books\":[1,2,3,4,5]}"

我有book 表与优惠券表无关

我还 CartVue.vue 文件,我将书籍存储在购物车中。 现在我想要一个名为getCouponArrtibute() 的属性,它将返回优惠券 其中$coupon->rules->books 具有来自购物车的特定图书 ID。

到目前为止,我已经做到了

public function getCouponAttribute()
{
    $discount = Coupon::whereJsonContains('rules->books', $this->id)->get();
    return $discount;
}

Cartvue.vue 开始,我现在可以访问优惠券属性,但每次无论图书 ID 是否在 coupon->rules->books 中,它都会返回 null 或空数组

【问题讨论】:

  • dd($discount->rules); 是做什么的回归?
  • @mrhn 它返回这个 "{"type":"percentage","discountPercent":"10","apply":1,"books":[1,2,3,4, 5],"categories":null,"selectedRequirement":1,"requirementValue":null,"selectedLimit":null,"usageLimitValue":null,"selectedEligibility":1}"

标签: php sql json laravel vue.js


【解决方案1】:

现在 Eloquent 认为 $discount->rulesstring。您需要将其转换为对象,这是通过使用 Eloquent Model $casts property 来完成的。这是通过在 Courpon.php model 上添加 casts 属性来完成的。

class Coupon {
    protected $casts = [
        'rules' => 'object',
    ];
}

这应该使访问$coupon->rules->books 工作。

【讨论】:

  • 那么它将变成一个数组,你不能做对象访问,你应该做 $coupon['rules']['books']
猜你喜欢
  • 2019-12-23
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多