【问题标题】:Laravel 4 to 5 upgrade: Eloquent relationships not workingLaravel 4 到 5 升级:雄辩的关系不起作用
【发布时间】:2015-03-13 14:35:28
【问题描述】:

我正在尝试将现有的 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 中运行良好。

【问题讨论】:

  • 你的模型有命名空间吗?

标签: php laravel-4 laravel-5


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多