雄辩的关系属性访问

时间:2018-05-26 16:39:12

标签: laravel

似乎无法在这里找出问题,收到错误 - Trying to get property 'name' of non-object

用户数据库

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('lastname');
        $table->string('email')->unique();
        $table->string('password');
        $table->integer('phone');
        $table->boolean('isAdmin')->default(0);
        $table->rememberToken();
        $table->timestamps();
    });

Sludinajums DB

 Schema::create('sludinajums', function (Blueprint $table) {
        $table->increments('id');
        $table->string('logo');
        $table->string('nosaukums');
        $table->string('regnr');
        $table->string('text');
        $table->string('atrasanasVieta');
        $table->string('adrese');
        $table->integer('telefons');
        $table->string('epasts');
        $table->integer('profesija_id')->unsigned();
        $table->foreign('profesija_id')->references('id')->on('profesijas')->onDelete('cascade');
        $table->integer('lietotajs_id')->unsigned();
        $table->foreign('lietotajs_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

用户模型功能

public function sludinajums()
{
    return $this->hasOne(sludinajums::class,'lietotajs_id');
}

Sludinajums模型功能

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

这是我的控制器功能

public function sludinajuma_skats($id){
    $slud = sludinajums::where('id',$id)->with('user')->get();

    return view('views.sludinajums', compact('slud'));
}

在我看来,我试图从用户表中访问名称属性。

{{dd($sl->user->name)}}

1 个答案:

答案 0 :(得分:0)

尝试使用Sludinajums模型函数

public function user()
{
    return $this->hasMany('App\User','lietotajs_id');
}