可以參考 How to join three table by laravel eloquent model
我也試過
ORM -> join('survey', 'survey.id', '=', 'survey_record.survey_id')
-> orderBy('survey.notification_time', 'desc')
這種方式,
有些特殊的語法需要自己嘗試,
不過方向大概是這樣...
今年鐵人賽剛好也在寫Laravel.
try this
join('orders', 'users.id', '=', 'orders.user_id','left outer')
嘗試過了,這個方法不行喔
目前Controller Code
$a=totalModel::select(
'total.area',
'total.vendor',
'total.barcode',
'total.name',
'total.unit',
'total.stock',
warehouseModel::raw("sum(warehouse2.num) as d"),
warehouseModel::raw("sum(warehouse2.outnum) as e"),
totalModel::raw("sum(total.stock) as r"),
)
->leftJoin('warehouse2',function ($join) {
$join->on('total.id', '=', 'warehouse2.total_id');})
->orwhere(function($c){
$c->wherebetween('total.area',[20, 50])
->wherebetween('warehouse2.ship_at',['2020-08-01','2020-08-31']);
})
->orwhere(function($query){
$query->wherebetween('total.area',[20, 50])
->wherebetween('warehouse2.purchase_at',['2020-08-01','2020-08-31']);
})
->groupBy(
'total.name',
'total.area',
'total.barcode',
'total.vendor',
'total.unit',
'total.stock'
)
->orderby('area','asc')
->get();
你要不要考慮,先拿掉其他部分只留join確定看看totalModel表的資料有沒有保留下來,正常left join totalModel表的資料都會被留下的
也會濾掉喔,目前設計是total表是所有商品的資訊,warehouse2是進出貨單建立的資訊表,報表想抓出total.area(是商品的擺放位置)20~50,但目前用join warehouse2表會把只有warehouse2的資料抓出,total.area20~50沒有在warehouse2不會出現
不會啊,我剛剛用laravel 7試了一下
A表的資料都有留下來
Join進來的B表欄位會有Null
那可以請教一下view那裏您怎麼寫的嗎
你先toSql()拿去sql那邊查一下出來的結果是不是你要的再來看view吧
或者可以把確定可以用的sql語法丟上來看看,看看是不是改寫ORM有改錯
我join這邊改成->join('warehouse2', 'total.id', '=','warehouse2.total_id','left outer')
結果還是一樣warehouse無建進出貨資料的,total.area還是無法顯示
改了一個sql,會濾掉total.area20~50 ,warehouse無建過資料的
select total.id, total.stock, total.area, sum(warehouse2.num), sum(warehouse2.outnum),
warehouse2.expiration_at,
warehouse2.ship_at
from total
left outer join warehouse2
ON total.id = warehouse2.total_id
where (total.area between 20 and 50)
and (month(warehouse2.purchase_at) = 8 or month(warehouse2.ship_at) = 8)
group by total.id
所以這個在sql裡面查出來是你要的結果嗎?
我看你原本的ORM裡面一堆groupby 這邊就一個
不是喔,Laravel orm select值 groupby要給
我不知道你要什麼所以幫你把你那串SQL改成ORM
$temp = totalModel::selectRaw('total.id, total.stock, total.area, sum(warehouse2.num), sum(warehouse2.outnum), warehouse2.expiration_at, warehouse2.ship_at')
->Join('warehouse2' , 'total.id', '=', 'warehouse2.total_id', 'left outer')
->where(function ($q){
$q->wherebetween('total.area', array(20,50));
})
->where(function ($q){
$q->whereRaw('month(warehouse2.purchase_at) = 8 or month(warehouse2.ship_at) = 8');
})
->groupby('total.id')
->get();