如何在Laravel中显示模型关系?

时间:2019-08-22 10:48:26

标签: php laravel eloquent

我有此数据库表:jobdepartmentpcn,此表pcn的属性为job_iddepartment_id。因此,在Laravel中,我在等效模型上有以下定义:

class Job extends Model
{
    public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Department extends Model
{
    public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Pcn extends Model
{
    public function job(){return $this->belongsTo('App\Job');}

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

我现在的问题是显示pcn列表的pcn索引给我这个错误:

Trying to get property 'name' of non-object (View: C:\wamp\www\bookersystem\resources\views\pcn\index.blade.php)

我的index.blade.php具有以下内容:

@foreach($pcns as $key => $value)
    <td>{{ $value->control_number }}</td>
    <td>{{ $value->job->name }}</td>
    <td>{{ $value->department->name }}</td>
@endforeach

在我的Pcn控制器上:

public function index()
{

    $pcns = Pcn::paginate(50);

    return view('pcn.index', compact('pcns'));

}

对于我的迁移,我有以下定义:

public function up()
{
    Schema::create('pcn', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->charset = 'utf8mb4';
        $table->collation = 'utf8mb4_general_ci';
        $table->bigIncrements('id');
        $table->unsignedBigInteger('department_id');
        //$table->foreign('department_id')->references('id')->on('department');
        $table->unsignedBigInteger('job_id');
        //$table->foreign('job_id')->references('id')->on('job');
        $table->string('control_number', 45);
        $table->string('center', 5);
        $table->string('status', 8)->nullable();
        $table->unsignedBigInteger('mrf_id')->nullable();
        $table->string('degree', 25)->default('Not Recruiting');
        $table->timestamps();
    });
}

我在这里做错了吗?

2 个答案:

答案 0 :(得分:2)

更恰当的做法是,从关系定义中删除id或声明 right foreign key

class Job extends Model
{
    //this
    public function pcns(){return $this->hasMany('App\Pcn');}
    //or this
    public function pcns(){return $this->hasMany('App\Pcn', 'job_id', 'id');}
}

class Department extends Model
{
    //this
    public function pcns(){return $this->hasMany('App\Pcn');}
    //or this 
    public function pcns(){return $this->hasMany('App\Pcn', 'department_id', 'id');}
}

第二步:最好是建立eager load关系以减少所需的查询数量:

public function index()
{
    $pcns = Pcn::with(['job', 'department'])->paginate(50);

    return view('pcn.index', compact('pcns'));
}

在那之后,您实际上并不需要$key=>$value中的@foreach

@foreach($pcns as $pcn)
    <td>{{ $pcn->control_number }}</td>
    <td>{{ $pcn->job->name }}</td>
    <td>{{ $pcn->department->name }}</td>
@endforeach

答案 1 :(得分:1)

paginate()方法不返回Pcn的集合,它返回一个LengthAwarePaginator,当转换为数组时,它具有作为索引(total,{{1 }},per_page ....)

您需要从next_link恢复

LengthAwarePaginator

顺便说一句,您应该在查询中预加载@foreach($pcns as $pcn) <td>{{ $pcn->control_number }}</td> <td>{{ $pcn->job->name }}</td> <td>{{ $pcn->department->name }}</td> @endforeach job关系,以便仅向数据库发送 3个请求,而不是 101 >。

department