【问题标题】:belongsTo method returning nullbelongsTo 方法返回 null
【发布时间】:2015-06-07 15:24:54
【问题描述】:

我有两个模型一个名为Customer 第二个是Website

他们之间的关系是,Customer hasMany Website while Website belongsTo Customer

我就是这样做的

class Website extends \Eloquent {
    use SubscriptionBillableTrait;

    protected $fillable = [];

    protected $guarded = ['id'];

    public function customermodel()
    {
        // Return an Eloquent relationship.
        return $this->belongsTo('Customer')
    }

}

Customer型号

use Mmanos\Billing\CustomerBillableTrait;
class Customer extends \Eloquent {
    use CustomerBillableTrait;
    protected $fillable = [];

    protected $guarded = ['id'];

    public function websites() {
        return $this->hasMany('Website');
    }

}

当我尝试通过这样的关系访问 Customer

$website = Website::find(1);
return dd($website->customermodel);

返回空值

注意:我使用的是 Laravel 4

【问题讨论】:

  • Eloquent 关系中的那些类名不应该包含完全限定的命名空间$this->belongsTo('App\Customer');(这很可能仅适用于您使用 Laravel 5,但您尚未指定)。
  • 在声明关系时使用全命名空间,例如$this->hasMany('App\Models\Website');$this->belongsTo('App\Models\Customer');。这行得通吗?
  • @Bogdan 我正在使用 Laravel 4,所以我认为这不会是触发因素
  • 您是否尝试过在return $this->belongsTo('Customer', 'local_key') 中指定本地密钥?
  • 您的websites 表是否有一个名为customer_id 的字段?另外,您确定网站 1 有相关客户吗?

标签: php laravel laravel-4 eloquent


【解决方案1】:

使用这个

$website = Website::find(1)->with('customermodel');
return dd($website->customermodel);

【讨论】:

  • 两个问题:首先,急切加载无济于事。访问$website->customermodel 属性将延迟加载数据,然后将其发送到dd() 方法。其次,find() 将返回模型。然后您在模型上调用with(),这将返回一个新的查询构建器,因此下一行将尝试访问查询构建器上的customermodel 属性,这将引发异常。您需要在实际检索数据的方法之前使用with() 方法:Website::with('customermodel')->find(1)
猜你喜欢
  • 2020-05-16
  • 2016-03-31
  • 2021-05-29
  • 1970-01-01
  • 2020-12-22
  • 2016-02-29
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
相关资源
最近更新 更多