Consultations with laravel

2

I recently started with laravel and I have a terrible doubt. I've done several google searches that only left me more confused yet. I have a news table and a photo table. Each news item has several photos. In home you have to see the last two news and the relevant photo. In pure sql I do this:

$sql = "SELECT * FROM noticias ORDER BY id_noticias DESC limit 2";
$res = $conexao->query($sql);
$dado= $res->fetch_assoc();

$sql_foto2= "select * from fotos where id_noticia =".$dado['id_noticias']; 

In the photo table, the id_notice field is linked to the primary key id_news of the noticias table.

How do I do this in Laravel?

photos table id_fotos (auto_increment and primary key) Address id_noticia

news table id_news (auto_increment and primary key) text title folder

object(Illuminate\Database\Eloquent\Collection)#197 (1) 
{ ["items":protected]=> array(2) 
{ [0]=> object(App\Noticias)#200 (25) 
{ ["table":protected]=> string(12) "not_noticias" ["primaryKey":protected]=> string(11) "id_noticias" ["timestamps"]=> bool(false) ["fillable":protected]=> array(7) 
{ [0]=> string(5) "texto" [1]=> string(6) "titulo" [2]=> string(7) "legenda" [3]=> string(5) "pasta" [4]=> string(9) "subtitulo" [5]=> string(6) 
"evento" [6]=> string(13) "titulo_evento" } ["connection":protected]=> string(5) "mysql" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true)
["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true)
["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(11) { ["id_noticias"]=> int(2246) ["texto"]=> string(689) 
"O curso de Enfermagem da Unifadra,...." ["titulo"]=> string(98) "Curso de Enfermagem da Unifadra Dracena desenvolve projeto Aproximação Prática Enfermagem (APE)" 
["legenda"]=> string(49) "Alunas do curso de Enfermagem da Unifadra Dracena" ["pasta"]=> string(4) "2242" ["subtitulo"]=> string(0) "" 
["evento"]=> string(0) "" ["titulo_evento"]=> string(0) "" ["data"]=> string(10) "2017-07-05" ["usuario"]=> string(8) "noticias" ["ativa"]=> string(1) "s" } 
["original":protected]=> array(11) { ["id_noticias"]=> int(2246) ["texto"]=> string(689) "O curso de Enfermagem da Unifadra,....
["titulo"]=> string(98) "Curso de Enfermagem da Unifadra Dracena desenvolve projeto Aproximação Prática Enfermagem (APE)" 
["legenda"]=> string(49) "Alunas do curso de Enfermagem da Unifadra Dracena" ["pasta"]=> string(4) "2242" ["subtitulo"]=> string(0) "" 
["evento"]=> string(0) "" ["titulo_evento"]=> string(0) "" ["data"]=> string(10) "2017-07-05" ["usuario"]=> string(8) "noticias" 
["ativa"]=> string(1) "s" } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) {
 } ["events":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(1)
 { ["fotos"]=> object(Illuminate\Database\Eloquent\Collection)#199 (1) { ["items":protected]=> array(0) { } } } ["touches":protected]=> array(0) {
 } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } } [1]=> object(App\Noticias)#201 
 (25) { ["table":protected]=> string(12) "not_noticias" ["primaryKey":protected]=> string(11) "id_noticias" ["timestamps"]=> bool(false)
 ["fillable":protected]=> array(7) { [0]=> string(5) "texto" [1]=> string(6) "titulo" [2]=> string(7) "legenda" [3]=> string(5) "pasta" [4]=> string(9) 
 "subtitulo" [5]=> string(6) "evento" [6]=> string(13) "titulo_evento" } ["connection":protected]=> string(5) "mysql" ["keyType":protected]=> string(3)
 "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) 
 ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(11) { ["id_noticias"]=> int(2245) ["texto"]=> string(2403) 

I'm finding that the problem is when I return to view. in the view looks like this:

@foreach ($noticias as $key=> $not)
    <div class="col-md-6">
         <div class="panel-heading">
              <img src={{asset('public/'.$not->endereco)}}>
              <h4>{{ $not->titulo }}</h4>
              <p align="justify">
                  <a href="#" class="noticia">
                     {{$texto = substr($not->texto,0,150)." ..."}}
                   </a>
              </p>
          </div>
    </div> 
@endforeach

No controller looks like this:

public function index()
    	{

        $noticias = Noticias::with(['fotos' => function($query){
                    $query->take(1); 
                 }])
                ->orderBy('id_noticias','DESC')
                ->take(2)
                ->get();
        //return view('inc.noticias')->with('query_noticias',$noticias);
        return view('inc.noticias',compact('noticias'));
    }            

Inthecaseofthephototable,thenamefieldIamnotusing.WhatIneedtogetreturnedistheaddressfield.Thisfieldnamewillberemoved.Thefoldersexistontheserverwiththesamenamesthatarestoredinthenewstable.

Therelationshipoftablesisasfollows:

MODELS

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Model\Noticias;
class Fotos extends Model
{
    protected $table = 'not_fotos';
    protected $primaryKey = 'id_foto';
    public $timestamps = false;
    protected $fillable = [
    	'nome',
    	'endereco',
    	'id_noticia'
    ];
   public function noticia(){
        return $this->belongsTo(Noticias::class);
    }
}
?>

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Noticias extends Model
{
    protected $table = 'not_noticias';
    protected $primaryKey = 'id_noticias';
    public $timestamps = false;
    protected $fillable =[
    	'texto',
    	'titulo',
    	'legenda',
    	'pasta',
    	'subtitulo',
    	'evento',
    	'titulo_evento'
    ];
    public function fotos()
            {
                return $this->hasMany(Fotos::class,'id_noticia','id_noticias'); 
            }
}
?>
    
asked by anonymous 05.07.2017 / 14:53

1 answer

2

I'm going to propose a minimal example, in fact if your relationship says in the comment it's correct ( I believe that the keys are non-standard and needs to be configured ) just do the following:

Minimum example:

Look at the configuration of the relationship by stipulating the keys:

class Noticia extends Model 
{
    public function fotos()
    {
        return $this->hasMany(Fotos::class,'id_noticia','id_noticias'); 
    }
}

For your SQL , just do this:

$noticias = Noticia::with('fotos')
    ->orderBy('id_noticias','DESC')
    ->take(2)
    ->get();

In this case you will bring all the news and all the corresponding photos, but if you want to optimize the number of photos for 1 ( on the screen I believe to be a photo ) like this:

$noticias = Noticia::with(['fotos' => function($query)
    {
        $query->take(1);
    })
    ->orderBy('id_noticias','DESC')
    ->take(2)
    ->get();

06.07.2017 / 14:48