我正在尝试将现有的Laravel 4项目升级到版本5。
模型关系不正常。每次我尝试从property_price
表访问属性时,它都返回null。
我的模型位于App/Models
目录。
属性模型
class Property extends \Eloquent {
protected $guarded = array('id');
protected $table = 'properties';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $softDelete = true;
public function propertyPrice()
{
return $this->hasOne('PropertyPrice','pid');
}
}
PropertyPrice模型
class PropertyPrice extends \Eloquent {
protected $guarded = array('id');
protected $table = 'property_pricing';
public function property()
{
return $this->belongsTo('Property');
}
}
用法
$property = Property::find($id);
$price = $property->property_price->per_night_price; // null
Laravel 4中的代码工作正常。
答案 0 :(得分:0)
您需要在关系方法中指定命名空间。
如果您使用 php5.5 + ,请使用::class
常量,否则使用字符串文字:
// App\Models\PropertyClass
public function property()
{
return $this->belongsTo(Property::class);
// return $this->belongsTo('App\Models\Property');
}
// App\Models\Property model
public function propertyPrice()
{
return $this->hasOne(PropertyPrice::class,'pid');
// return $this->hasOne('App\Models\PropertyPrice','pid');
}
当然,您需要相应地命名模型:
// PSR-4 autoloading
app/Models/Property.php -> namespace App\Models; class Property