Lavarel-相关错误:调用模型[App \ Nota]上未定义的关系[nota]

问题描述 投票:0回答:3

我想用口才做以下查询:

$nota=DB::table('notas')
        ->join('users', 'users.id', '=', 'notas.id_user')
        ->select('notas.id','notas.nombre', 'notas.descripcion', 'users.name AS user_name', 'users.email')
        ->first();

我尝试在模型中建立关系,并在控制器中这样调用:

public function show($id)
{

    $nota = Nota::with(['user','nota'])->first();
    print_r($nota);

    return view("notas.detalle", compact("nota"));
}

但是我得到以下错误:

照亮\数据库\锋\ RelationNotFoundException调用模型[App \ Nota]上未定义的关系[nota]。

我的模型如下所示:Nota.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

user.php的:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function notas()
    {
        return $this->hasMany('App\Nota');
    }    
}
php laravel model relation
3个回答
0
投票

问题出在此功能Nota::with(['user','nota'])->first()

您为什么要Nota和Nota。听起来可笑,不是吗?

所以只需将其删除,然后一切都会正常。

$nota = Nota::with(['user'])->first();

return view("notas.detalle", compact("nota"));

0
投票

您只能将用户传递给nota,因为nota模型已经被调用。

use App\Nota;
use App\User;

          public function show($id)
          {
            $nota = Nota::with(['user'])->first();
            return view("notas.detalle", compact("nota"));
          }

0
投票

问题在于您对关系的理解。您没有建立任何名为nota的关系,但您正在使用它,并且荒谬地使用了相同的模型。因此,首先使用naming convention建立正确的关系。

Nota模型中

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

User模型中

public function notas()
    {
        return $this->hasMany('App\Nota','id_user');
    }

现在在控制器中

$nota = Nota::with('user')->first();

return view("notas.detalle", compact("nota"));

看起来这是一个渴望的加载。您也可以延迟加载关系。

现在查看中,您可以访问对象属性,如

{{ $nota->nombre }} 

和类似关系的对象

{{ $nota->user->email }}
© www.soinside.com 2019 - 2024. All rights reserved.