欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel SQL查询中first, pluck与lists list 方法的使用 数据库中某个列名 某个列的所有列名 得到 所有的行的所有列 指定列 指定字段信息 单独列名 单个列名 自己亲自做的 有大用 有大大用 有大大大用

下面的可能新版本 有问题  可以见见  /node-admin/14933
$this
->wx_users()->where('article_wx_user.wx_user_id',
Session::
get('curr_wx_user_id'))->
pluck(
'article_wx_user.article_wx_user_is_shoucang')->first();

说明与总结

由运行结果截图我们不能得出这3个方法的区别。

  • first 方法是取得结果集数组中第一列数据,如果结果集为空则返回 null 。

  • pluck 方法是取得结果集第一列特定字段,它返回是Collections;可以含多个值

  • lists 方法是按照 key=>value 对的方式返回数组;它的参数最多两个,第一个参数作为键值(value),第二个参数作为键名(key)。lists 如果后面只有一个参数,它的结果与 pluck 是一样的 

  • value 方法是得到第一行的第一列   var_dump(Yuanzhang::where('yuanzhang_name','like','%长%')->value('yuanzhang_id')); 到虽然用pluck list get 等方法可以有多个结果, 但是这里只得到唯一的值是 1  

标签:none





var_dump(Customer::where('customer_name', '阿妙')->pluck('customer_name'));
var_dump("AAAAAAAA");
var_dump(\DB::table('customers')->where('customer_name', '阿妙')->pluck('customer_name'));
var_dump("BBBBBBBBB");


object(Illuminate\Support\Collection)#296 (1) {  #通过模型的pluck获取的是集合Collection  可以见见  /node-admin/14933
 ["items":protected]=>
 array(1) {
   [0]=>
   string(6) "阿妙"
 }
}
string(8) "AAAAAAAA"
array(1) {               #通过 \DB的pluck获取的是数组array   可以见见  /node-admin/14933
 [0]=>
 string(6) "阿妙"
}
string(9) "BBBBBBBBB"





   var_dump(Customer::where('customer_name', '阿妙')->lists('customer_name'));
   var_dump("CCCCCCCCC");
   var_dump(\DB::table('customers')->where('customer_name', '阿妙')->lists('customer_name'));
   var_dump("DDDDDDDDDD");

object(Illuminate\Support\Collection)#296 (1) {    #通过模型的lists获取的是集合Collection  可以见见  /node-admin/14933


  ["items":protected]=>

  array(1) {

    [0]=>

    string(6) "阿妙"

  }

}

string(9) "CCCCCCCCC"

array(1) {                             #通过 \DB的lists获取的是数组array    可以见见  /node-admin/14933


  [0]=>

  string(6) "阿妙"

}

string(10) "DDDDDDDDDD"


20150324140951.jpg

看到说明文档上面介绍,难免有些迷惑,还是亲自动手试试吧。

sql测试数据表

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', '张三', 'zhangsan@example.com', '$2y$10$DNXpTLallazQRUTfFjsmx.qe0lr8SjoM1f2B5muNFB6Fn4Ay/DVIa', null, '2015-03-24 14:48:37', '2015-03-24 14:48:41');
INSERT INTO `users` VALUES ('2', '李四', 'lisi@example.com', '$2y$10$6sK8ZZjHgK8kYxnceIrmoO1RdrXdOxZxbxFyFgpNlZI83ZHI9nO6y', null, '2015-03-24 14:49:39', '2015-03-24 14:49:42');

控制器测试方法

    public function test()
    {
        $users = DB::table('users')->get();
        $user = DB::table('users')->where('name', '张三')->first();
        $name = DB::table('users')->where('name', '张三')->pluck('name');
        $names = DB::table('users')->lists('name');
        $name_email = DB::table('users')->lists('name','email');
        var_dump($users, $user, $name, $names, $name_email);
    }

运行结果

20150324150659.jpg

说明与总结

由运行结果截图我们不能得出这3个方法的区别。

  • first 方法是取得结果集数组中第一列数据,如果结果集为空则返回 null 。

  • pluck 方法是取得结果集第一列特定字段,它返回是字符串;

  • lists 方法是按照 key=>value 对的方式返回数组;它的参数最多两个,第一个参数作为键值(value),第二个参数作为键名(key)。

标签:none

Laravel how to return single column value using Query Builder

I want to use the data from the SQL Query, to explain it further here is my code:

    $myquery = DB::table('attendances')->select('user_id')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();

    $myquery->user_id;

Now I want the value of my $myquery to be USER_ID's value, I get error if I used the Above code -$myquery->user_id;

  • The error?????? – Nabil Kadimi Nov 26 '14 at 8:36
  • 1
    I think it's because you're not retrieving a single result. so, if you want the user_id, you can iterate over $myquery, or select the first result )->first() – GiuServ Nov 14 '16 at 13:58
  • As @GiuServ said : get() will return an array of attendance objects even if there is only one object matched the where conditions. Where first() will return the first matched object from the result. Even more than one object is matched where conditions. – Bhaskar Rajoriya Nov 3 '17 at 6:25 

EDIT: As of version 5.1 pluck is deprecated, since 5.2 its meaning is completely different (as lists used to be), so use value method instead.


You're trying to get property of the array, so obviously you're getting error.

If you need single field only, then use pluck (which returns single value - string by default):

// let's assume user_id is 5

DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->pluck('user_id');  // "5"

When you need whole row, then first (which returns stdObject):

$att = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->first();

$att->user_id; // "5"
$att->any_other_column;

And get is when you want multiple results (which returns simple array of stdObjects):

$result = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->get();

$result; // array(0 => stdObject {..}, 1 => stdObject {..}, ...)
$result[0]->user_id; // "5"

That's for Laravel 5.3:

$user_id = DB::table('attendances')->select('user_id')->where('date_only', '=', $newdate)->orderBy('logon','asc')->value('user_id');

This will return user_id only

$myquery = DB::table('attendances')->where('date_only', $newdate)->select('user_id')->pluck('user_id')->first();

I think there is some confusion; but I am using Laravel 5.3 and pluck and value function is not deprecated as depicted above.

For more clarification: pluck() will be used instead of get() when you want all the values only value()will be used instead of first() when you want only one value.

use method all() to get the array of itmes. usage:

\App\User::whereIn('mobile',['971700000', '965000000'])->select('id')->pluck('id')->all();
 $myquery = DB::table('attendances')->select('user_id')
            ->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();

by default, the returned data will be array of objects. you need to loop over it.

e.g.

foreach($myquery as $i)
{
    echo $i->user_id;
}

来自  https://stackoverflow.com/questions/27143961/laravel-how-to-return-single-column-value-using-query-b...


普通分类: