Laravel连接并从多个表中选择 [英] Laravel join and select from multiple tables

查看:91
本文介绍了Laravel连接并从多个表中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有Laravel 5.2,在我的SQL数据库中,我有几个表: books ,其中包含字段titleauthoryear journals ,其中包含字段titleyearprice newspapers ,其中包含字段titletownyear

So I have Laravel 5.2 and in my SQL database I have several tables: books with fields title, author and year, journals with fields title, year and price newspapers with fields title, town, year

我需要从1994年开始的所有三个表中获取所有标题的列表.我尝试执行以下操作

I need to get a list of all titles from all three tables, where the year is 1994. I've tried to do the following

$titles = DB::table('books')->where('books.year', 1994)->leftjoin('journals as journals', 'books.year', '=', 'journals.year')->leftjoin('newspapers as newspapers', 'books.year', '=', 'newspapers.year')->select('books.title', 'journals.title', 'newspapers.title')->get();

但是通过此查询,我得到的条目充满了null,并且只填写了报纸.我在做什么错了?

But with this query I get entries full of nulls, and only newspapers are filled in. What am I doing wrong?

推荐答案

在这种情况下(如果表不相关),您应该使用并集,而不是联接.

In this case (if the tables are not related) you should use union, no join.

$books = DB::table('books')->select('title')->where('year', 1994);
$journals = DB::table('journals')->select('title')->where('year', 1994);
$titles = DB::table('newspapers')->select('title')->where('year', 1994)->union($books)->union($journals)->get();

这篇关于Laravel连接并从多个表中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆