Join in Laravel 5.x in two tables?

3

I have two tables that are already related in MySQL and I use Laravel , I'm already persisting the information in the database. When I write a story, it is already assigned to the author (tables autor and news ).

At the time of listing news , I did the following method on NewsControllers

public function listar()
{
        $news= News::all();
        return view('listar')->with('news', $news);
}

Then when I want to display them in views, I do

@foreach ($news $n)
    <tr>
        <td>{{ $n->id}}</td>
        <td>{{ $n->conteudo}}</td>
    </tr>
@endforeach

And it works perfectly.

My question would be, how do I display the author's name in that listing and in that list method?

[news]

id
titulo
conteudo
autor (FK com id de autores)

[authors]

id
nome
    
asked by anonymous 03.05.2017 / 21:36

2 answers

3

This also works:

public function listar()
{
        $news= News::join('autor', 'news.autor', '=', 'autor.id')
            ->select('news.id', 'titulo', 'conteudo', 'nome')
            ->get();
        return view('listar')->with('news', $news);
}
    
03.05.2017 / 21:51
2

To use all features of Eloquent you should add the relationships as follows:

<?php namespace App;     

   use Illuminate\Database\Eloquent\Model; 

   class News extends Model 
   {
        protected $table = 'news'; 
        public $timestamps = true; 
        public function autor()
        {       
            return $this->belongsTo('App\Autores', 'autor', 'id');      
        }
    }

In the controller method call the relation with with :

public function listar()
{
    $news= News::with('autor')->get();
    return view('listar')->with('news', $news);
}

And in your view :

@foreach ($news as $n)
    <tr>
        <td>{{$n->id}}</td>
        <td>{{$n->conteudo}}</td>
        <td>{{$n->autor->nome}}</td>
    </tr>
@endforeach
    
03.05.2017 / 21:42