首页 > 解决方案 > Laravel belongsTo 关系不返回值

问题描述

我正在尝试运行 hasMany,但我真的不知道为什么我没有得到任何结果!两个表:公司,工作订单,每个工作订单都有一个公司名称和地址,我想在 laravel 中使用 belongsTo 关系获取

<?php
namespace App;

class Company extends Model
{
    protected $table      = 'company';
    protected $primaryKey = 'company_id';

    public function jobs() {
        return $this->hasMany('App\Joborder');
    }
}

我的工作订单页面

<?php
namespace App;

class Joborder extends Model
{
    protected $table      = "joborder";
    public    $primaryKey = "joborder_id";
    protected $dates      = [
        'start_date',
        'created_at',
        'updated_at'
    ];

    public function company() {
        return $this->belongsTo('App\Company');
    }
}
    

这是页面控制器:

public function joblist() {
    $joblist     = Joborder::all();
    $newInstance = new Joborder;
    $company     = $newInstance->company();

    dd($company->name);
    dd($joblist);

    return view('pages.joblist')->with('jobs',$joblist);
} 

这是运行后我页面中的 dd

BelongsTo {#217 ▼
  #foreignKey: "company_id"
  #otherKey: "company_id"
  #relation: "company"
  #query: Builder {#218 ▶}
  #parent: Joborder {#205 ▼
    #table: "joborder"
    +primaryKey: "joborder_id"
    #dates: array:3 [▼
      0 => "start_date"
      1 => "created_at"
      2 => "updated_at"
    ]
    #guarded: array:1 [▼
      0 => "id"
    ]
    #fillable: []
    #connection: null
    #keyType: "int"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: []
    #original: []
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: false
    +wasRecentlyCreated: false
  }
  #related: Company {#212 ▼
    #table: "company"
    #primaryKey: "company_id"
    #guarded: array:1 [▼
      0 => "id"
    ]
    #fillable: []
    #connection: null
    #keyType: "int"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: []
    #original: []
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: false
    +wasRecentlyCreated: false
  }
}

我在公司中有 company_id 作为 pkey,在 joborder 中有 fkey 感谢您的帮助!

标签: phplaravellaravel-5eloquent

解决方案


你应该打电话

$company = $newInstance->company()->get();

代替

$company = $newInstance->company();

PageController:jobList.
现在,您不是通过相关数据来恢复关系本身。

或者,您可以company作为属性访问,该属性应自动返回相关数据而不是关系本身:

$company = $newInstance->company;

推荐阅读