2015-03-13 123 views
1

我正在嘗試將現有的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中工作正常。

+0

您模型命名空間? – 2015-03-13 14:44:40

回答

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