我正在尝试从Laravel中的查询生成器获取单个值,但是问题是我正在获取数组。 这是我在邮递员中使用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']);
如何从喜欢而不是从数组中获取单个值?
答案 0 :(得分:1)
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->is_liked;
首先调用将返回1个结果,而不是一个数组,然后可以调用所需的列。
我相信您也可以这样称呼它:
$previous_is_liked = NewsCommentLike::query()->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])->first()->value('is_liked')
答案 1 :(得分:1)
这就是为什么您使用->value('my_column')
方法的原因。因此,您将得到:
NewsCommentLike::query()
->where(['user_id' => $user_id, 'news_comment_id' => $newsComment->id])
->value('is_liked');
优点是可以直接从数据库中检索值。如果您在
first()
之前调用它,则它可以为null,从而破坏您的代码。