[英]Laravel 8 Inner Join Two Tables
I'm trying to get different columns from two tables in my Laravel database, I'm new to joins but following the docs I think my syntax is correct, except I get the following error:我试图从我的 Laravel 数据库中的两个表中获取不同的列,我是 joins 新手,但是按照文档我认为我的语法是正确的,除了我收到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in on clause is ambiguous (SQL: select `data_source_one`.`event_count`, `data_source_two`.`sessions` from `data_source_one` inner join `data_source_two` on `created_at` >= `2021-01-11 10:57:45`)
I have two tables:我有两张桌子:
Each table has the Laravel created_at
column, one table has a sessions
column, the other has event_count
, and I have data for 14 days prior to my query.每个表都有 Laravel
created_at
列,一个表有一个sessions
列,另一个有event_count
,我有查询前 14 天的数据。 So not sure why it can't get the data?所以不知道为什么它无法获取数据?
My PHP is:我的 PHP 是:
public function getSources(Request $request)
{
$data = DB::table('data_source_one')
->join('data_source_two', 'created_at', '>=', Carbon::now()->subDays(14))
->select('data_source_one.event_count', 'data_source_two.sessions')
->get();
return response()->json($data, 200);
}
As indicated in the error message, the "created_at" column is ambiguous because it's present in both tables.如错误消息中所示,“created_at”列不明确,因为它存在于两个表中。 So you have to specify which "created_at" you are referring to.
所以你必须指定你指的是哪个“created_at”。
Maybe like this:也许是这样的:
$data = DB::table('data_source_one as DSO')
->join('data_source_two as DST', //here, join your two tables by a common column )
->select('DSO.event_count', 'DST.sessions')
->where('DST.created_at', '>=', Carbon::now()->subDays(14))
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.