【发布时间】: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