Laravel 4到5升级:雄辩的关系不起作用
问题描述:
我正在尝试将现有的Laravel 4项目升级到版本5. 模型关系无法正常工作。每次我尝试访问property_price
表中的属性时,它都会返回null。Laravel 4到5升级:雄辩的关系不起作用
我的模特儿位于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
鳕鱼e在Laravel 4中工作正常。
答
您需要在关系方法中指定名称空间。
如果您使用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
您模型命名空间? – 2015-03-13 14:44:40