简体   繁体   English

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

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

I'm trying to get a single value from Query Builder in Laravel but the problem is I'm getting an array. 我正在尝试从Laravel中的查询生成器获取单个值,但是问题是我正在获取数组。 this is my query result in Postman with dd($myVar): 这是我在邮递员中使用dd($ myVar)的查询结果:

[{"is_liked":1}]

and also with echo($myVar): 以及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 => "*"
      ]
    }
  ]
}

and my code is: 我的代码是:

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

How to get a single value from is_liked not an array? 如何从is_liked而不是数组中获取一个值?

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

Calling first returns 1 result instead of an array, then you can call the column you want. 首先调用将返回1个结果,而不是一个数组,然后可以调用所需的列。

I believe you could also call it like this: 我相信您也可以这样称呼它:

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

This is why you have ->value('my_column') method. 这就是为什么要使用->value('my_column')方法的原因。 So you'll end up with: 因此,您将得到:

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. 如果在它之前调用first() ,则它可以为null,从而破坏您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM