【问题标题】:How to get value of only single column using eloquent model如何使用 eloquent 模型仅获取单个列的值
【发布时间】:2023-04-03 08:55:02
【问题描述】:

这是我的对象

{
   "id":1,
   "name":"abc",
   "tech":"PHP"
}

现在我想首先使用 laravel 收集方法使用用户雄辩模型来获得技术价值 这是我雄辩的模型查询

$tech = User::select('tech')->first();

但它返回的数据是这样的对象形式

{"tech":"PHP"}

我只想要字符串格式中的值而不是对象中的值,就像它应该返回“PHP”一样。 有人可以帮忙吗?

【问题讨论】:

    标签: php laravel collections eloquent


    【解决方案1】:

    你的代码

    $tech = User::select('tech')->first();
    

    如你所说

    其实它会返回对象

    {"tech":"PHP"}
    

    试试这个来得到结果

    $tech = User::select('tech')->first()->tech;
    

    不像

    $tech = User::select('tech')->first();
    

    【讨论】:

      【解决方案2】:

      您可以为此使用pluck 函数。

      $tech = User::pluck('tech')->first();
      

      这将返回:

      "php"
      

      【讨论】:

      • 很高兴我能帮上忙。考虑将此标记为您问题的答案,以便其他用户也可以找到此解决方案。
      猜你喜欢
      • 2020-01-06
      • 2015-06-05
      • 2021-11-28
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      相关资源
      最近更新 更多