查询构建器 Laravel

时间:2021-03-17 09:03:28

标签: laravel-5

我有一张桌子来存放我的文章。我这张桌子上没有照片,我的照片在另一张桌子上。我添加了 5 个帖子,每个帖子有 3 张图片。现在我想得到 5 个帖子,每个帖子只需要 3 张图片中的 1 张,怎么办?我需要帮助,谢谢

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

使用 Laravel 的关系函数, 将此添加到您的 Post 模型:

public function images()
{
    return $this->hasMany(YourImageModel::class);
}

对于您的查询,请使用:

$post = Post::find($id)->with('images')->first();
$allImages = $post->images;
$firstImage = $post->images->first();

如果您想要所有带有图片的帖子:

$posts = Post::with('images')->get();

在你的刀片中:

@foreach($posts as $post)
    {{ $post->images->first() }}
@endforeach