当hasOne什么都没有时,Laravel错误

时间:2014-10-29 10:36:01

标签: php laravel laravel-4

我正在尝试预先填充表单中的某些字段,而且我是关系中的新手。

我的控制器:

public function index($supplierId) {
    $Supplier = new Supplier;
    $supplierData = Supplier::find($supplierId);
    $supplierData->countryId = ($supplierData->countryId == 0 ? 258 : $supplierData->countryId);
    $supplierData->writtenLanguageId = ($supplierData->writtenLanguageId == 0 ? 1 : $supplierData->writtenLanguageId);
    $supplierData->paymentTermsId = ($supplierData->paymentTermsId == 0 ? 5 : $supplierData->paymentTermsId);
    $countries = Countries::lists('country', 'id');
    $languages = Languages::lists('language', 'id');
    $paymentTerms = PaymentTerms::lists('term', 'id');
    $leadTimes = Leadtimes::lists('leadtime', 'id');
    return View::make('supplier.supplier', array(
                'supplierData' => $supplierData,
                'countries' => $countries,
                'languages' => $languages,
                'paymentsTerms' => $paymentTerms,
                'leadtimes' => $leadTimes
    ));
}

我的模特:

class Supplier extends Eloquent {
    protected $table = 'suppliers';

    public function email() {
        return $this->hasOne('SupplierEmail', 'supplierId');
    }

    public function creditLimits() {
        return $this->hasOne('SupplierCreditLimits', 'supplierId');
    }

    public function website() {
        return $this->hasOne('SupplierWebsite', 'supplierId');
    }
}

问题:

<div class='col-xs-12 col-md-6'>{{Form::text('website', $supplierData->website->website, array('class' => 'form-control input-sm'))}}</div>

当没有行(没有记录)时,我得到:

Trying to get property of non-object (View: C:\wamp\vhosts\view\laravel\app\views\supplier\supplier.blade.php)

如何使其正常工作?

1 个答案:

答案 0 :(得分:1)

在您的视图中,使用isset首先检查值:

<div class='col-xs-12 col-md-6'>
    {{Form::text('website', 
      isset($supplierData->website->website) ? $supplierData->website->website : '', 
      array('class' => 'form-control input-sm'))
    }}
</div>

或者,更好的是,在控制器中处理此逻辑并将结果传递给视图:

$supplierData->URL = isset($supplierData->website->website) ? $supplierData->website->website : '';