Foreach with PHP Stdclass

Asked

Viewed 319 times

3

My page shows posts that have been registered in the database. Some posts have files that have been uploaded. These files are saved in server folders and the database has the table "Archive" with the columns ID, Post, Name and Size.

$postagens = DB::table('postagens')
                ->where('dsa', '=', $id)
                ->OrderBy('Data_publicacao', 'Desc')
                ->get();

foreach ($postagens as $postagem => $post)
{
  $arquivos_postagens[$post['Id_postagem']] = DB::table('arquivos_postagens')
  ->where('postagem','=', $post['Id_postagem'])
  ->first();
}

I am now trying to use the foreach above to scroll through the posts and perform another select in the "Archive" table where the "post" column receive the post id value and store the result in another array so that I send it to the page and can work with each one of them.

However, it’s not working. I searched and saw some Array videos in PHP but I couldn’t get the information I needed. Could you help me?

Thank you

Bench:

Table Posts Fields: Id_postagem, data_publicacao, description, disciplina (dsa), Title

Table Archive_posts Fields: File Id_name, Post(Id_post), Size

Select desired:

Assuming the Id_post is equal to 5 I want to return a table like this:

Id_file Name Post Size
3 reades.txt 5 1024
4 photo.jpg 5 6780
5 class.pdf 5 12304

  • Put in your question the two tables and relation fields that will be shown in select... What is the version of your Laravel?

  • 1

    My Standard is 5.3. I will make the edits in the question by putting what you requested.

  • The relationship is 1 postagem has several Arquivo_postagens?

  • 1

    This Virgilio. A post may have 0 or multiple files...

  • I made an answer!

2 answers

3

I don’t know if your class DB allows you to execute query queries, but, you could try Joins.

a practical example for this your query would be:

SELECT p.*, ap.dado1, ap.dado2, ap.dado3 FROM postagens p
JOIN Arquivos_postagem ap
ON p.dsa = ap.postagem
WHERE dsa = {$id}
ORDER BY Data_publicacao DESC

Where on lines 2 and 3 I join another table to pull the data from it and on line 1 I specify between SELECT and FROM what data I want from each table. Read on here to learn more about Joins.

  • It helped, I will check if in future methods I can apply this concept. I thought about doing it this way at first. But in this case that I presented would not work because my table "arquivos_postagens" does not have the column of "DSA" (q is the ID of the discipline that has the posts). Only the column "post" q points to the Id_post in the table "posts" that already has the discipline ID rs

  • 2

    Please don’t put it on "I hope I’ve helped" at the end of your responses. Follow the discussion in Meta. This is text considered irrelevant to the site.

0

If the relationship is 1 for many could be done Eloquent Model, that will facilitate the loading of their relationships:

Postings

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Postagens extends Model
{
    protected $primaryKey = 'ID_Postagem';
    protected $fillable = array('data_publicacao',
                                'descricao',
                                'dsa',
                                'titulo');
    protected $table = 'Postagens';
    public $timestamps = false;
    // aqui seria a relação de 1 para muitos...
    public function arquivos()
    {
        return $this->hasMany(ArquivoPostagens::class, 'postagem','ID_Postagem');
    }

}

Archiving

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ArquivoPostagens extends Model
{
    protected $primaryKey = 'ID_arquivo';
    protected $fillable = array('nome',
                                'postagem',
                                'tamanho');
    protected $table = 'Arquivo_postagens';
    public $timestamps = false;
    // relação onde 1 ArquivoPostagens é de uma postagem
    public function postagem()
    {
        return $this->belongsTo(Postagens::class, 'postagem','ID_Postagem');
    }

}

How to use:

To carry the relationship use the command with, so that at the moment of creation the:

$postagens = Postagens::with(['arquivos'])
                      ->where('dsa', '=', $id)
                      ->orderBy('Data_publicacao', 'Desc')
                      ->get();

Within the variable $postagens if there is a relation it will have an item arquivos with the relation of the files to that determined $postagens. That way you don’t have to worry about searching separately for the files, itself has the function to bring the data according to the relation. I see no reason then to use DB:: in this case by the fact of performance that for each item of the posting is made a Select, this can cause a certain slowness in the loading process.

References:

  • A question Virgilio: Which folder should I put the file of these Models in Laravel?

  • Particularly I create inside the folder app a briefcase Models (app\Models), and the namespace App\Models (as in the example code). This is a pattern that had and they removed, for me should never have left. Normal creation is spread (well that’s right) in the folder app.

Browser other questions tagged

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