我正在使用PHP 5.5.12和MYSQL 5.6.17开发Laravel5上的项目 昨天一切都很好,但是当我今天回到我的代码时, 我有错误"试图获得非对象的属性"在多个模型对象上,这种情况经常发生在与其他模型有关系时。
如果我写这个:
IPAddressAccessControlHandler
我收到了错误。
如果我写这个:
$test = $model->relation->property;
然后打印没有问题。
我真的不知道会发生什么,任何帮助都会非常感激。
Ps:对不起如果我写的文字错了,这是我第一次在stackoverflow上问问题:) 哦,我确实已经阅读了所有类似的问题
这是Stay.php模型:
echo / var_dump($model->relation->property);
这是相关的型号:
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Stay extends CustomModel {
protected $table = 'stay';
protected $fillable = array('reservation_terms_convention_id', 'reservation_id', 'period_id', 'total_price', 'price_ht', 'occupant_id', 'prestation_fixe_id', 'pax', 'checkin', 'checkout');
protected $guarded = array('id');
static public $mailTemplatingWhitelist = ['total_price'];
public static $rules = [
'reservation_terms_convention_id' => 'required|exists:reservation_terms_convention,id',
'period_id' => 'required|exists:period,id',
'payeur_id' => 'required'
];
public function payment_due_date()
{
return $this->belongsTo('App\models\PaymentDueDate','payment_due_date_id', 'id');
}
}
最后是控制器:
<?php namespace App\models;
use Illuminate\Database\Eloquent\Model;
class PaymentDueDate extends CustomModel {
protected $table = 'payment_due_date';
protected $fillable = array('total_amount', 'acompte_amount', 'amount_ht', 'amount_already_payed', 'payment_total_date', 'payment_acompte_date',
'facturation_date', 'description_facture', 'type', 'cash_desk_id', 'individual_customer_id',
'partner_id', 'direction');
protected $guarded = array('id');
public function stay(){
return $this->hasOne('App\models\Stay');
}
}
答案 0 :(得分:0)
首先,如果你写
var_dump($doesnotexists1->doesnotexists2->doesnotexists3);
它的null,没有错误,因为var_dump查找$ doesnotexists1,如果它为null,它将不会进一步查找。所以你没有得到“试图在Execption中获得非对象的属性。”
所以,你的问题可能是$ stay或$ stay-&gt; payment_due_date at
$amount = $stay->payment_due_date->total_amount;
为空/空。
我会检查它
foreach ($partner_resa as $key => $resa) {
foreach ($resa->stays as $key => $stay) {
if(is_object(stay) && is_object($stay->payment_due_date)) {
$amount = $stay->payment_due_date->total_amount;
}
}
}
确保它是一个对象