【问题标题】:Fetch first image from foreign key table Laravel从外键表 Laravel 中获取第一张图片
【发布时间】:2019-06-21 11:21:38
【问题描述】:

参考:Fetch first image from foreign key table 但这次是在 Laravel。

我开始使用 Laravel,我想从每个帖子中获取第一张图片,并在我的刀片中展示这些图片。

$secondpost = DB::table('posts')
        ->orderBy('id', 'desc')
        ->skip(1)
        ->take(8)
        ->get();

foreach ($secondpost as $spost)
$secondph = DB::table('post_images')
        ->select('filename')
        ->where('post_id', $spost->id)
        ->limit(1)
        ->get()
        ->pluck('filename');

return view ('pages.index', compact('firstp', 'fph', 'secondpost', 'secondph'));
<div class="row">
 @foreach ($secondpost as $secondp)
 <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
  <div class="row">
   @foreach ($secondph as $sph);
    <img src="{{url($sph)}}" class="imgpost" alt="">
   @endforeach
    <div class="bottomleft">
      <p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
      <p class="ab-desc">{{$secondp->pret}} Eur</p>
    </div>
    </div>
   </div>
 @endforeach
</div>

此代码只为每个 img src 加载一张图片。 post_id 是posts表id的外键。

【问题讨论】:

  • “第一张图片”是什么意思?链接到帖子的第一张图片?您可以尝试按“created_at”列对图像进行降序排序,然后仅选择第一个结果。
  • 在您的代码中,$secondph 的值在每个循环中不断变化。您只能从循环的最后一次迭代中获得值。您应该将每个循环中的值存储到一个数组中并将该数组传递给刀片。

标签: php mysql laravel


【解决方案1】:

您需要确认的事项很少。

  1. 您已经为表创建了模型,例如 Postposts 表和 PostImagespost_images 表。如果没有,请遵循文档。 https://laravel.com/docs/5.8/eloquent

  2. 您已在 post 模型中与 post_images 创建了 hasMany 关系。喜欢:

Post 模型中。

/**
* Get the images for the post.
*/
public function images()
{
    return $this->hasMany('App\PostImage');
}
  1. 然后将控制器更改为使用早期加载,例如:

$secondpost = \App\Post::with("images")
        ->orderBy('id', 'desc')
        ->skip(1)
        ->take(8)
        ->get();

现在视图看起来像:

<div class="row">
 @foreach ($secondpost as $secondp)
 <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
  <div class="row">
    @php
        $image = $secondp->images->first();
    @endphp
    <img src="{{url($image->filename)}}" class="imgpost" alt="">
    <div class="bottomleft">
      <p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
      <p class="ab-desc">{{$secondp->pret}} Eur</p>
    </div>
    </div>
   </div>
 @endforeach
</div>

解决方案:2

您可以与hasOne 创建另一个关系以获取单个图像,例如:

// In your Post model.

/**
* Get the default image for post.
*/
public function default_image()
{
    return $this->hasOne('App\PostImage')->orderBy("id");
}

更改控制器以使用-&gt;with("default_image")

在视图中你可以使用如下:

    $secondp->default_image->filename

【讨论】:

  • 感谢您的回复!我改变了,现在 "->with("images")" 给了我错误:调用未定义的方法 Illuminate\Database\Query\Builder::with() 。我用谷歌搜索了它,但没有结果。
  • 使用 \App\Post 代替 Db::table('posts)` 在解决方案中更新。确保您的模型位于App 目录中或相应地更改路径。
  • @VasiliuRobert 这有帮助吗?
  • 当然!我也遇到了一些列名问题,但我解决了。非常感谢!!!
猜你喜欢
  • 2011-11-08
  • 2016-10-07
  • 2011-12-28
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2019-12-29
相关资源
最近更新 更多