Php belongsTo方法返回null
我有两个模型一个名为Php belongsTo方法返回null,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有两个模型一个名为客户第二个是网站 它们之间的关系是,Customer有许多Website,而Website属于Customer 我就是这样做的 class Website extends \Eloquent { use SubscriptionBillableTrait; protected $fillable = []; protected $guarded = ['id']; public function customermodel() {
客户
第二个是网站
它们之间的关系是,Customer
有许多Website
,而Website
属于Customer
我就是这样做的
class Website extends \Eloquent {
use SubscriptionBillableTrait;
protected $fillable = [];
protected $guarded = ['id'];
public function customermodel()
{
// Return an Eloquent relationship.
return $this->belongsTo('Customer')
}
}
客户
型号
use Mmanos\Billing\CustomerBillableTrait;
class Customer extends \Eloquent {
use CustomerBillableTrait;
protected $fillable = [];
protected $guarded = ['id'];
public function websites() {
return $this->hasMany('Website');
}
}
当我试图通过这样的关系访问客户时
$website = Website::find(1);
return dd($website->customermodel);
它返回空值
注意:我使用的是Laravel 4
$website = Website::find(1)->with('customermodel');
return dd($website->customermodel);
雄辩关系中的那些类名不应该包含一个完全限定的名称空间$this->belongsTo('App\Customer')代码>(这很可能仅在使用Laravel 5时适用,但尚未指定)。在声明关系时使用完整名称空间,例如,$this->hasMany('App\Models\Website')
和$this->belongsTo('App\Models\Customer')代码>。这行得通吗?@Bogdan我使用的是Laravel 4,所以我不认为这是触发因素。您是否尝试过在return$this->belongsTo('Customer','local\u key')
中指定本地密钥?您的网站表中是否有一个名为Customer\u id
的字段?另外,您确定Website1有相关客户吗?有两个问题:第一,急于加载不会有帮助。访问$website->customermodel
属性将延迟加载数据,然后将其发送到dd()
方法。其次,find()
将返回模型。然后在模型上调用with()
,这将返回一个新的查询生成器,因此下一行将尝试访问查询生成器上的customermodel
属性,这将引发异常。在实际检索数据的方法之前,需要使用with()
方法:Website::with('customermodel')->find(1)
。