1
votes

I want to make the following query with 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();

I try to make the relation in the models and called like this, in my controller:

public function show($id)
{

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

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

But i get the follow error:

Illuminate\Database\Eloquent\RelationNotFoundException Call to undefined relationship [nota] on model [App\Nota].

My models looks like this: 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');
    }    
}
2
there is no nota in your model change it to notas. beside this code might not stop because both models are related to each other.Babak Asadzadeh

2 Answers

1
votes

The problem is with your understanding of relationship. You don't make any relationship named nota but you are using it and ridiculously with the same model. So firstly make the relationship right using naming convention.

In Nota model

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

In User model

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

And now in controller

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

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

Look this is an eager loading. You can lazy load the relationship too.

In view now you can access object property like

{{ $nota->nombre }} 

And relationship object like

{{ $nota->user->email }}
0
votes

The problem is with this function Nota::with(['user','nota'])->first()

Why do you want nota with nota. it's sounds ridiculous isn't it?

So just remove it, then everything will work fine.

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

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