问题描述
我有这样的数据库设置:https://imgur.com/a/ECOypAE
我的代码是这个
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Apartment;
use Auth;
use App\Rate;
use Braintree;
use App\Sponsorship;
use App\Payment;
use Carbon\Carbon;
public function index(Sponsorship $sponsorship)
{
//definisco la data di scadenza con CARBON
$current_timestamp = Carbon::now('Europe/Rome')->toDateTimeString();
//recupero la sponsorizzazione in database più recente,dell'appartamento in oggetto
$apartment = Apartment::all()->where("id","=",$sponsorship->apartment_id)->where("expiry_date",">",$current_timestamp);
dd($apartment);
我想做的是仅显示在赞助表中Apartment Id等于apartment_id的公寓,以及赞助未过期的公寓。
结果我得到一个空数组。
我认为我在建立错误的查询:有什么想法吗?
谢谢
解决方法
调用all()
后,查询将运行并返回数据库中的所有结果。
在get()
之后使用where()
获得想要的结果
$apartment = Apartment::where("id","=",$sponsorship->apartment_id)->where("expiry_date",">",$current_timestamp)->get();
如果您希望某些功能正常工作,请尝试
if ($sponsorship && $sponsorship->expiry_date > $current_timestamp ) {
$apartment = Apartment::find($sponsorship->apartment_id);
} else {
//no valid sponsorship
$apartment = null;
}
,
这里可能是您想要的东西,您应该在Channing方法的最后调用'get()'方法而不是'all()',并使用该关系获取这种结果,请检查以下内容代码,其中有控制器方法和模型方法,希望会对您有所帮助。
#Controller方法
public function index(Sponsorship $sponsorship)
{
$current_timestamp = Carbon::now('Europe/Rome')->toDateTimeString();
$apartment = Apartment::with('sponsorship')
->whereHas('sponsorship',function($query)use($sponsorship,$current_timestamp) {
$query->where('id',$sponsorship->id)
->where('expiry_date','>',$current_timestamp);
})->get();
dd($apartment);
}
#Model关系方法
公寓模型
public function sponsorship()
{
return $this->hasOne('App\Sponsorship','apartment_id','id');
}
在这里,我假设您的模型具有“具有一种关系”,这意味着 公寓没有多个赞助商。