【发布时间】:2021-03-30 22:01:59
【问题描述】:
有人知道如何查询这个示例表吗?
我认为这是从表 branches 到表 branch_operationals 的左连接,我应该将 where date 放入查询中。
以下是示例:
表格branches
| id | code | name |
|---|---|---|
| 1 | T2QD5 | NewYork_Spot |
| 2 | MKGHB | London_Spot |
| 3 | IGHCZ | Miami_Spot |
| 4 | PJDSO | Tokyo_Spot |
表格branch_operationals
| id | branch_id | date | status |
|---|---|---|---|
| 1 | 2 | 2020-12-05 | closed |
| 2 | 2 | 2020-12-06 | closed |
| 3 | 3 | 2020-12-06 | open |
| 4 | 2 | 2020-12-06 | closed |
| 5 | 2 | 2020-12-06 | open |
| 6 | 1 | 2020-12-16 | closed |
预期结果
| id (from 'branches.id') | code | name | date | status |
|---|---|---|---|---|
| 1 | T2QD5 | NewYork_Spot | 2020-12-09 | closed |
| 2 | MKGHB | London_Spot | 2020-12-09 | open |
| 3 | IGHCZ | Miami_Spot | 2020-12-09 | open |
| 4 | PJDSO | Tokyo_Spot | 2020-12-09 | null |
这是我当前的查询:
select * from `branches` left join `branch_operationals` on `branches`.`id` = `branch_operationals`.`branch_id` where (`date` = 2020-12-21)
但是,它返回 null(空数据)。但是当我删除where 语句时,它会显示表branch_operationals 中的所有数据以及表branches 中的每个数据。
目前我使用的是 Laravel 8,这是我的 Laravel 语法:
$branches = Branch::leftJoin('branch_operationals','branches.id','branch_operationals.branch_id')->where(function($q) use($request){
if($request->search){
$q->where(function($q) use($request){
$q->where('code','like','%'.$request->search.'%');
$q->orWhere('name','like','%'.$request->search.'%');
});
}
if($request->date_filter){
$q->where('date',$request->date_filter);
}else{
$q->where('date',\Carbon\Carbon::now()->toDateString());
}
})->get();
我需要查询语法或 Laravel Eloquent 语法。
谁能帮帮我?感谢您的关注:)
【问题讨论】:
标签: php mysql sql laravel eloquent