简体   繁体   中英

Laravel 4 to 5 upgrade: Eloquent relationships not working

I'm trying to upgrade my existing Laravel 4 project to version 5. Model relationships are not working fine. Every time I try to access a property from property_price table it returns null.

My models are located in App/Models directory.

Property Model

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 Model

class PropertyPrice extends \Eloquent {

    protected $guarded = array('id');

    protected $table = 'property_pricing';

    public function property()
    {
        return $this->belongsTo('Property');
    }

}

Usage

$property = Property::find($id);
$price = $property->property_price->per_night_price; // null

The code is working fine in Laravel 4.

You need to specify namespace in relation methods.

If you're using php5.5+ then use ::class constant, otherwise string literal:

// 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');
}

Of course you need to namespace the models accordingly:

// PSR-4 autoloading
app/Models/Property.php -> namespace App\Models; class Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM