2017-05-15 100 views
1

使用accepted answer here,我想根據created_at返回所有對象。如何在日期爲字符串時查詢日期表

$projects = [ {id => 1,..., 'created_at' => "2017-05-15 14:46:32",...}, ] 

$time = strtotime('2017-05-15'); // format issue? 

$newformat = date('Y-m-d',$time); // "2017-05-15" 

$projects = $user->projects->where('created_at', $newformat); 

即時得到回$projects空數組,在tinker相同。是的,雄辯是完美的。我以正確的方式去做嗎?

既然我在這裏,我需要查詢兩個日期,即$from$towhereBetween

$projects = $user->projects->whereBetween('created_at', [$from, $to])->toArray(); 

我不記得在那裏我看到從whereBetween但給我的錯誤: $from$to會類似於$newformat

Method whereBetween does not exist.

+0

'$ projects = $ user-> projects-> whereBetween('created_at',[$ from,$ to]) - > get();'你試過這個嗎? –

+0

https://laravel.com/docs/5.2/queries#where-clauses –

+0

@QuỳnhNguyễn我,是的,我已經嘗試過,但不斷收到'方法whereBetween不存在。我需要將它添加到我的模型嗎?對不起,我是laravel的新手。我有一個閱讀。謝謝 – Sylar

回答

3

你需要指定projects的方法,而不是一個屬性:

$projects = $user->projects()->where('created_at', $newformat)->get(); 

嘗試訪問$user->projects沒有()將返回一個Collection,它沒有whereBetween方法。您將不得不使用:

$user->projects()->whereBetween('created_at', [$from, $to])->get(); 

在那種情況下。請注意,Collections有一個where方法,但它的工作方式與Eloquent不一樣。

https://laravel.com/docs/5.4/collections#method-where

如果你要查詢的日期,我覺得最好用whereRaw()

$user->project()->whereRaw("DATE_FORMAT(`created_at`, '%Y-%m-%d') BETWEEN '".$from."' AND '".$to."'"); 

如果只查詢一個日期:

$user->project()->whereRaw("DATE_FORMAT(`created_at`, '%Y-%m-%d') = '".$newFormat."'"); 

我應該還可以添加有一個whereDate()子句可用作上述的簡寫:

https://laravel.com/docs/5.4/queries#where-clauses

$user->projects()->whereDate("created_at", $newFormat) 

還有whereYear()whereMonth()whereDay(),這可能是鏈接到搜索特定的日期。

+0

嗨。但是在修補程序中'App \ Project :: where(...)'仍然是一樣的 – Sylar

+0

可能是您的查詢問題。 'created_at'上有Hours,Minutes和Seconds,所以' - > where(「created_at」,$ newFormat)'會失敗。 –

+0

正確。這就是我的問題現在 – Sylar

1

你應該嘗試:

$newformat = date('Y-m-d',$time).'%'; // "2017-05-15" 

$projects = $user->projects()->where('created_at', 'like', $newformat); 
相關問題