Laravel 5.2 EagerLoading 关系 returns 空
Laravel 5.2 EagerLoading relationship returns null
我正在从 4.2 升级到 Laravel 5.2 并且 运行 遇到了一个奇怪的问题,当我在关系上使用 Eager Loading 时,它 returns 为 null,但我可以手动调用。
这是我的父模型:
namespace App\Models\Hours;
class Hours extends Model {
/**
* Model Setup
*/
protected $table = 'leave_hours';
protected $primaryKey = 'leave_id';
public $timestamps = false;
/**
* Relationships
*/
public function hoursStatus()
{
return $this->belongsTo('App\Models\Hours\HoursStatusType', 'leave_status_code');
}
这是 HoursStatusType 模型:
<?php
namespace App\Models\Hours;
use Illuminate\Database\Eloquent\Model;
class HoursStatusType extends Model {
/**
* Model Setup
*/
protected $table = 'leave_status_type';
protected $primaryKey = 'leave_status_code';
public $timestamps = false;
/**
* Relationships
*/
public function hours()
{
return $this->hasMany('App\Models\Hours\Hours');
}
}
基本上,Hours 的 PTO 请求具有状态(即待定、已批准等)。 HoursStatusType 只有 4 行,它属于许多 Hours 请求。
我在工作时间提出了一个很大的要求,例如:
$requests = Hours::with('hoursStatus')->get();
foreach($requests as $r){
print_r($r->hoursStatus);
}
当我尝试使用 foreach 循环打印出来时,hoursStatus 关系为空。但是,当我在没有急切加载的情况下调用它时,没关系。从 4.2 升级后我唯一改变的(除了添加命名空间)是将 hoursStatus 关系从 hasOne 更改为 belongsTo。另外几篇文章提到更改它应该可以解决它。没那么多。
我错过了什么吗?谢谢!
当 PK 不是自动递增的整数时,您应该将 public $incrementing = false;
添加到您的模型设置中。
我正在从 4.2 升级到 Laravel 5.2 并且 运行 遇到了一个奇怪的问题,当我在关系上使用 Eager Loading 时,它 returns 为 null,但我可以手动调用。
这是我的父模型:
namespace App\Models\Hours;
class Hours extends Model {
/**
* Model Setup
*/
protected $table = 'leave_hours';
protected $primaryKey = 'leave_id';
public $timestamps = false;
/**
* Relationships
*/
public function hoursStatus()
{
return $this->belongsTo('App\Models\Hours\HoursStatusType', 'leave_status_code');
}
这是 HoursStatusType 模型:
<?php
namespace App\Models\Hours;
use Illuminate\Database\Eloquent\Model;
class HoursStatusType extends Model {
/**
* Model Setup
*/
protected $table = 'leave_status_type';
protected $primaryKey = 'leave_status_code';
public $timestamps = false;
/**
* Relationships
*/
public function hours()
{
return $this->hasMany('App\Models\Hours\Hours');
}
}
基本上,Hours 的 PTO 请求具有状态(即待定、已批准等)。 HoursStatusType 只有 4 行,它属于许多 Hours 请求。
我在工作时间提出了一个很大的要求,例如:
$requests = Hours::with('hoursStatus')->get();
foreach($requests as $r){
print_r($r->hoursStatus);
}
当我尝试使用 foreach 循环打印出来时,hoursStatus 关系为空。但是,当我在没有急切加载的情况下调用它时,没关系。从 4.2 升级后我唯一改变的(除了添加命名空间)是将 hoursStatus 关系从 hasOne 更改为 belongsTo。另外几篇文章提到更改它应该可以解决它。没那么多。
我错过了什么吗?谢谢!
当 PK 不是自动递增的整数时,您应该将 public $incrementing = false;
添加到您的模型设置中。