我有一个表来存储我的文章。我在这张表中没有照片,我的照片在另一张表中。我添加了5个帖子,每个帖子有3张图片。现在我想得到5个帖子,每个帖子只拍3张照片中的1张,怎么办??我需要帮助,谢谢
在此处输入图像描述
在此处输入图像描述
使用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