Laravel 从具有列 key/value 的数据库中获取值
Laravel get value from db with columns key/value
我的数据库中有一个 table,其中包含这些列:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
我会按名称访问值。
例如我有这些数据:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
我会在 'start_date' 之前获得“2020-01-01”。
我尝试了这段代码,但我并不满意,因为使用这段代码我得到了该行的所有值,而不仅仅是预期的值。
Configuration::get()->keyBy('start_date');
我不确定我是否清楚。
告诉我。
非常感谢!!
假设你想得到一个 key/value 对的数组,并且 name
列中的每个键都是唯一的,你可以简单地使用 pluck()
(https://laravel.com/docs/8.x/collections#method-pluck) :
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
然后,您只需使用数组访问即可在适用的情况下使用这些配置设置:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...
我的数据库中有一个 table,其中包含这些列:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
我会按名称访问值。
例如我有这些数据:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
我会在 'start_date' 之前获得“2020-01-01”。
我尝试了这段代码,但我并不满意,因为使用这段代码我得到了该行的所有值,而不仅仅是预期的值。
Configuration::get()->keyBy('start_date');
我不确定我是否清楚。
告诉我。
非常感谢!!
假设你想得到一个 key/value 对的数组,并且 name
列中的每个键都是唯一的,你可以简单地使用 pluck()
(https://laravel.com/docs/8.x/collections#method-pluck) :
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
然后,您只需使用数组访问即可在适用的情况下使用这些配置设置:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...