拉拉维尔 4 到 5 升级:雄辩的关系不起作用


Laravel 4 to 5 upgrade: Eloquent relationships not working

我正在尝试将我现有的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');
     }
}

物业价格模型

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 中运行良好。

您需要在关系方法中指定命名空间。

如果您使用的是 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