关系已加载,但在我调用它时返回null

时间:2019-07-01 09:04:11

标签: laravel eloquent relationship eager-loading

我查询模型“ Royalty”并渴望加载关系“ Owner”。模型返回结果,包括关系。

class Royalty extends Model
{
    protected $guarded = [];
    protected $dates   = ['created_at', 'updated_at', 'date', 'calculated_at'];

    protected $casts = [
        'properties' => 'object',
    ];

    public function owner()
    {
        return $this->belongsTo(Owner::class);
    }
}

class Owner extends Model
{
    use SoftDeletes;
    protected $guarded = [];
    protected $dates    = ['created_at', 'updated_at', 'deleted_at'];

    protected $casts = [
        'properties' => 'object',
    ];


    public function royalties()
    {
        return $this->hasMany(Royalty::class);
    }
}

$royalty = Royalty::with('owner')->where('id', 1)->first();

结果符合预期,并且渴望拥有“所有者”关系:

Royalty {#542 ▼
  #guarded: []
  #dates: array:4 [▶]
  #casts: array:1 [▶]
  #connection: "development"
  #table: "royalties"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:21 [▶]
  #original: array:21 [▶]
  #changes: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "owner" => Owner {#562 ▼
      #guarded: []
      #dates: array:4 [▶]
      #casts: array:1 [▶]
      #connection: "development"
      #table: "owners"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #changes: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #forceDeleting: false
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

但是,当我使用$ royalty-> owner调用关系时,结果为NULL。我在这里做什么错了?

dd($royalty->owner); NULL

3 个答案:

答案 0 :(得分:1)

您必须使用可填充而不是受保护的。

class Royalty extends Model
{
    protected $fillable = [ 'id', ...];
    protected $dates   = ['created_at', 'updated_at', 'date', 'calculated_at'];

    protected $casts = [
        'properties' => 'object',
    ];

    public function owner()
    {
        return $this->belongsTo(Owner::class);
    }
}

答案 1 :(得分:1)

发生这种情况的主要原因有两个。

  • 一个是数据库中的信息具有更改器
  • 您已经在模型toArray()中重载了Owner方法(我知道您的示例中没有)

答案 2 :(得分:0)

您必须像这样定义您的关系,  在版税模式中,请定义

public function owner() { return $this->belongsTo(Owner::class,'owner_id'); }并在所有者模型中将id填写为可填充内容。

还有您的

public function royalties() { return $this->hasMany(Royalty::class); }很完美