假设我有 3 个表,posts
、post_images
和 post_links
。
post.id 是 post_images 和 post_links 中的外键。
每个帖子都有多张图片。
我需要一个包含帖子、其图像及其链接的数据作为单个元素/数组项。如果有 3 个帖子,我需要 3 个数组,每个数组包含帖子图片和链接。
到目前为止我的代码,
$data = DB::table('posts')
->join('post_images','posts.id' ,'=', 'post_images.post_id')
->join('post_links','posts.id' ,'=', 'post_links.post_id')
->select('posts.*')
->get();
通过上面的查询,我得到了所有的记录,如果我有 3 条记录,每条记录有 3 张图像,我得到 9 条记录,我只需要 3 个帖子及其数据作为其子数组。
有什么建议吗?
最佳答案
这是 PostImage 模型
类 PostImage 扩展模型
{
public function post() {
return $this->belongsTo(Post::class);
}
}
这是 PostLink 模型
class PostLink extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
}
这是 Post 模型
class Post extends Model
{
public function links() {
return $this->hasMany(PostLink::class);
}
public function images() {
return $this->hasMany(PostImage::class);
}
}
在 View 中,您可以找到所需的一切。
@foreach ($posts as $post)
{$post->title} <br>
@foreach ($post->links as $link)
{$link->url} <br>
@endforeach
@foreach ($post->images as $image)
{$image->src} <br>
@endforeach
@endforeach
如果您想使用更少的查询,您可以使用预加载来在第一时间获取所有这些数据。 Eager Loading Laravel
应该是这样的
$posts = Post::with('images','links')->get();
关于php - 从 3 个表中获取数据并将其显示为 laravel 中的单个元素的正确查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44659453/