我总是使用这个丑陋的代码从数据库中获取给定id的单个值
例如,我想获得一个网站的访问次数
// ============================================ getNumberOfVisits()
//
// website_name : ..
// return the number of visits for a given website
//
private function getNumberOfVisits($website_name)
{
$visits = Website::where('name', $website_name)->get(['number_of_visit']);
return $visits[0]['attributes']['number_of_visit'];
}
是否有另一种方法可以在给定where语句的情况下从特定列中获取数据库中的单个值?
答案 0 :(得分:3)
这个怎么样?
$website = Website::where('name', $website_name)->first(['number_of_visit']);
return $website->number_of_visit;
甚至更好:
$visits = Website::where('name', $website_name)->pluck('number_of_visit');
pluck()
实际上与我的第一个代码示例相同。这是来源:
public function pluck($column)
{
$result = $this->first(array($column));
if ($result) return $result->{$column};
}