【问题标题】:Lavarel - Error in relation: Call to undefined relationship [nota] on model [App\Nota]Laravel - 关系错误:调用模型 [App\Nota] 上的未定义关系 [nota]
【发布时间】:2020-01-28 19:39:43
【问题描述】:

我想用 Eloquent 进行以下查询:

$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"));
}

但我收到以下错误:

Illuminate\Database\Eloquent\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');
    }
}

用户.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');
    }    
}

【问题讨论】:

  • 您的模型中没有 nota 将其更改为 notas。这段代码旁边可能不会停止,因为这两个模型是相互关联的。

标签: php laravel model relation


【解决方案1】:

问题在于你对关系的理解。您没有建立任何名为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 }}

【讨论】:

    【解决方案2】:

    问题出在这个函数Nota::with(['user','nota'])-&gt;first()

    为什么要 nota 和 nota。这听起来很荒谬不是吗?

    所以只要删除它,一切都会好起来的。

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

    【讨论】:

    • 很好,工作。但我想获取 users.email 字段。结果不明白。
    • 不可能,可以通过$nota-&gt;user-&gt;email访问用户邮箱
    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 2018-05-23
    • 2019-11-17
    • 1970-01-01
    • 2020-01-31
    • 2019-12-01
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多