Laravel数据库查询失败



我有一个这样的数据库设置:https://i.stack.imgur.com/nmnfv.jpg

我的代码是这个

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppApartment;
use Auth;
use AppRate;
use Braintree;
use AppSponsorship;
use AppPayment;
use CarbonCarbon;
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()后,将运行查询并返回DB中的所有结果。

where()之后使用get()获得想要的结果

$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((",并使用关系来获得这种结果。查看下面的代码,有控制器方法和模型方法。希望它能对你有所帮助。

#控制器方法

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);
}

#关系的模型方法

公寓模型

public function sponsorship()
{
return $this->hasOne('AppSponsorship', 'apartment_id', 'id');
}

在这里,我假设你的模型有"有一种关系",这意味着公寓没有一个以上的赞助。

最新更新