Php Laravel雄辩的一对一关系设置
我在一个laravel应用程序中设置了一对一的关系,但是当我尝试引用一个相关的表时,我得到了错误“尝试获取非对象的属性” My Contractor.php模型:Php Laravel雄辩的一对一关系设置,php,laravel,laravel-4,Php,Laravel,Laravel 4,我在一个laravel应用程序中设置了一对一的关系,但是当我尝试引用一个相关的表时,我得到了错误“尝试获取非对象的属性” My Contractor.php模型: class Contractor extends Eloquent { /** * The database table used by the model. * * @var string */ protected $table = 'contractor'; function profile() {
class Contractor extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contractor';
function profile() {
return $this->hasOne('ContractorProfile');
}
}
My ContractorProfile.php模型:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ContractorProfile extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'contractor_profile';
public function contractor() {
return $this->belongsTo('Contractor');
}
}
问题可能是因为您的
承包商
模型使用了非标准表名。通过将第二个参数指定为belongsTo
,尝试在您的ContractorProfile
模型中定义关系:
return $this->belongsTo('Contractor', 'contractor_id');
您可能还需要在承包商
模型上执行相同的映射:
return $this->hasOne('ContractorProfile', 'contractor_id');
你能发布数据库模式的相关部分吗?真的只需要看看你使用的身份证我觉得一切都很好。尝试使用
$contractor=contractor::with('contractorProfile')->查找(1)
,并在您的视图中尝试dd($contractor->profile)
并确保属性存在。我添加了$contractor=contractor。。。行到我的控制器,dd($contractor->…)到我的视图,收到一个致命的异常错误。感谢您的帮助。ContractorProfile表中没有匹配的contractor\u id。一旦我将相应的记录添加到表中,一切都很好。感谢您的建议。不幸的是,这也不起作用。
return $this->belongsTo('Contractor', 'contractor_id');
return $this->hasOne('ContractorProfile', 'contractor_id');