Consultations with Laravel

Asked

Viewed 671 times

2

I started recently with Laravel and I have a terrible doubt. I have done several searches on google that have only left me even more confused. I have a table of news and a table of photos. Each news has several photos. In home The last two news and their featured photo must appear. In pure sql I do so:

$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 there is the field id_noticia connected with the primary key id_noticias table noticias.

Like I do it in Laravel?

table photos id_photos (auto_increment and primary key) addressee id_noticia

news table id_noticias (auto_increment and primary key) text title briefcase

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 thinking the problem is time for me to return to view. in view is 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

On the controller it’s 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'));
    }            

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

In the case of the photo table, the name field I am not using. What I need to return is the address field. This name field will be removed. Folders exist on the server with the same names that are stored in the news table.

The list of tables is like this: inserir a descrição da imagem aqui

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'); 
            }
}
?>

  • You made the Model of these two tables and placed the relationships?

  • 1

    Hello @Virgilionovic! In the news model I put like this: 'public Function fotos(){ Return $this->hasMany(Photos::class); }'.

  • is right the relationship and some problem your there? if ever gave a var_dump($noticias) in return? if you can do this and put in your question?

  • @Virgilionovic, I already gave a var_dump yes, but the result is too big for me to post here.

  • Glue only one record?

  • in this var_dump does not return any photo and your view also has problems I think it is in your tables that the problem has! have to do a fine-tooth comb to know why the code is correct, the problem is in the information stored, have to send a print of the two tables with the data.?

  • Gisele the intriguing thing is that it’s all right and my answer fits in there, it gets complicated to say something because maybe it’s silly, put both Models News and Photos in your question lacked this to draw the last conclusion. ? Another thing test solution 1 also to see what happens without the take!

  • Gisele cadê the belongsTo that in mine has its no ... It lacks this to return the values. hasMany also has look there on.my example. The view is in trouble too

  • @Virgilionovic, I’m sorry, but I don’t understand... do you mean the models or the chart? I confess that I am lost and worse, being pressured because I need to do it here for my service... If it is in the model, it is there yes, look there! And what’s wrong with the view???

  • I imagine you really have to put relationships in each other too everything in Model

  • I’ve reached a point where I’d better give up. I don’t know what else to do...

Show 6 more comments

1 answer

2

I will propose a minimal example, actually if your relationship stated in the comment is correct (I believe that the informed keys are outside the standard and need then be configured) I’ll tell you what:

Minimal example:

Note the relationship setting setting the keys:

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

For his SQL just do it like 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) could do so:

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

References

  • Hello, @Virgilionovic! I did it the way suggested. The news returned, but the photos did not. In the news model I put in a photos Function what suggested to me: 'Return $this->hasMany(Photos::class,'id_noticia','id_noticias'); '

  • @Giselepassoni passes the two tables in your question! is to work yes, and something else has record in the tables? but, pass the layout of the two tables!

  • Excellent @Virgilionovic!

  • do not use pure sql in the model, use the query Builder (Eloquent) as Virgilio showed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.