如何从 Laravel 中的查询生成器获取单个值?

How to get a single value from Query Builder in Laravel?

我试图从 Laravel 中的查询生成器获取单个值,但问题是我获取的是一个数组。 这是我在 Postman 中使用 dd($myVar) 的查询结果:

[{"is_liked":1}]

还有 echo($myVar):

Collection {#976
  #items: array:1 [
    0 => NewsCommentLike {#970
      #fillable: array:3 [
        0 => "user_id"
        1 => "news_comment_id"
        2 => "is_liked"
      ]
      #connection: "mysql"
      #table: "news_comment_likes"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:1 [
        "is_liked" => 1
      ]
      #original: array:1 [
        "is_liked" => 1
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [
        0 => "*"
      ]
    }
  ]
}

我的代码是:

$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->get(['is_liked']);

如何从 is_liked 而不是数组中获取单个值?

$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->is_liked;

首先调用returns1个结果而不是数组,然后你可以调用你想要的列。

我相信你也可以这样称呼它:

$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->value('is_liked')

这就是为什么你有 ->value('my_column') 方法。所以你最终会得到:

NewsCommentLike::query()
    ->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])
    ->value('is_liked');

The advantage is that the value is retrieved directly from the database. If you call first() before it, it can be null thus break your code.