【问题标题】:How do i select one image from a result list of images?如何从图像结果列表中选择一张图像?
【发布时间】:2020-01-06 21:56:52
【问题描述】:

我有一个用于帖子的图像表。每个帖子可能有多个图像。我只想为任何帖子获取其中一张图片。

这是我想在 MySQL 上使用 vanilla PHP 实现的目标:

SELECT disk_image_filename FROM Vehiclepostimages WHERE (vehicleposts_id = ' . $id . ') ORDER BY id ASC LIMIT 1

但我无法让它在 Laravel 中工作。这是我在 Laravel 中的代码:

$image = Vehiclepostimages ::where([ 
            ['Vehicleposts_id', '=', $id],
        ])->value('disk_image_filename')->orderBy('id ASC')->get();

【问题讨论】:

  • 如果您在循环之外调用图像,它将为您提供其中一张图像,或限制 1

标签: php mysql laravel eloquent


【解决方案1】:

orderBy 的语法不正确。

$image = Vehiclepostimages::where('Vehicleposts_id', $id)
              ->value('disk_image_filename')
              // Takes two parameters. Default for 2nd is 'ASC'
              ->orderBy('id', 'ASC')
              ->get();

【讨论】:

    【解决方案2】:

    Value 获取第一条记录,你也不需要使用 get()。

    $image = Vehiclepostimages::where('Vehicleposts_id', $id)
                  ->orderBy('id', 'ASC')
                  ->value('disk_image_filename');
    

    【讨论】:

      【解决方案3】:

      谢谢大家。这就是最终奏效的方法:

      /** Logic for getting a vehicle's top or first image data from the image table */
      public function topImage($id)
      {
          $image = Vehiclepostimages ::where('Vehicleposts_id', $id)
                ->orderBy('id', 'ASC')->first();
      
          return $image;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 2023-01-04
        • 2013-09-04
        • 2014-07-01
        • 1970-01-01
        • 2018-10-24
        相关资源
        最近更新 更多