从 3 个表中获取数据并将其显示为 laravel 中的单个元素的正确查询?
A correct query to get data from 3 tables and show it as a single element in laravel?
假设我有 3 个表,posts
、post_images
和 post_links
。
post.id 是 post_images 和 post_links 中的外键。
每个 post 有多个图像。
我需要一个数据,其中包含 post、其图像和链接作为单个 element/array 项。如果有 3 个 post,我需要 3 个数组,每个数组包含 post 个图像和链接。
到目前为止我的代码,
$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 posts 及其数据作为其子数组.
有什么建议吗?
如果你已经在模型中有关系,你只需要使用 with
方法,比如
$data = PostModel::with('post_images','post_links')->get();
让它成为 dd($data)
看看这个。希望它会起作用。
参考文献: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
这里是Post图片模型
class Post图像扩展模型
{
public function post() {
return $this->belongsTo(Post::class);
}
}
这是Post链接模型
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);
}
}
在视图中,您可以找到所需的一切。
@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();
假设我有 3 个表,posts
、post_images
和 post_links
。
post.id 是 post_images 和 post_links 中的外键。
每个 post 有多个图像。
我需要一个数据,其中包含 post、其图像和链接作为单个 element/array 项。如果有 3 个 post,我需要 3 个数组,每个数组包含 post 个图像和链接。
到目前为止我的代码,
$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 posts 及其数据作为其子数组.
有什么建议吗?
如果你已经在模型中有关系,你只需要使用 with
方法,比如
$data = PostModel::with('post_images','post_links')->get();
让它成为 dd($data)
看看这个。希望它会起作用。
参考文献: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading
这里是Post图片模型
class Post图像扩展模型
{
public function post() {
return $this->belongsTo(Post::class);
}
}
这是Post链接模型
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);
}
}
在视图中,您可以找到所需的一切。
@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();