我有一张桌子来存放我的文章。我这张桌子上没有照片,我的照片在另一张桌子上。我添加了 5 个帖子,每个帖子有 3 张图片。现在我想得到 5 个帖子,每个帖子只需要 3 张图片中的 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