D
D
Div-Man2018-09-04 13:52:33
Laravel
Div-Man, 2018-09-04 13:52:33

How to display category for posts?

I am using a many-to-many relationship.
It is necessary to display a list of posts, which category the post belongs to, I did it using the builder, because I don’t know how to do it through the ORM.
3 tables:
categories
-id
-name
images
-id
-image
-description
category_image (intermediate)
-image_id
-category_id

public function getCategoryTitle($id)
    {  
        $post = DB::table('category_image')
                     ->where('image_id', '=', $id)
                     ->get();
        $categoryImage = $post->toArray()[0]->category_id;
       
       
        $showCategory = DB::table('categories')
                     ->where('id', '=', $categoryImage)
                     ->get();
       
       return $showCategory->toArray()[0]->name;
       
    }

Now it turns out that for each post, there will be 2 more requests to the database, and this is very bad.
posts like this
public function index()
    {
        $posts = Image::all();
     
        return view('admin.posts.index', ['posts'=>$posts]);
    }

@foreach($posts as $post)
                <tr>
                  <td>{{$post->id}}</td>
                  <td>{{$post->description}}</td>
                  <td>{{$post->getCategoryTitle($post->id)}}</td>
                  <td>

/////////////////////////////////////////////////// ////////////////
Tried with ORM
dd( $this->belongsToMany(
            Category::class,
            'category_image',
            'image_id',
            'category_id',
                1
        ));

And how now to display the name of the category?
шина	
BelongsToMany {#494 ▼
  #table: "category_image"
  #foreignPivotKey: "image_id"
  #relatedPivotKey: "category_id"
  #parentKey: 1
  #relatedKey: "id"
  #relationName: "getCategoryTitle"
  #pivotColumns: []
  #pivotWheres: []
  #pivotWhereIns: []
  #pivotValues: []
  +withTimestamps: false
  #pivotCreatedAt: null
  #pivotUpdatedAt: null
  #using: null
  #accessor: "pivot"
  #query: Builder {#493 ▶}
  #parent: Image {#473 ▶}
  #related: Category {#490 ▶}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin, 2018-09-13
@potkot

I did something like this
Model for articles:

class Articles extends Model
{
    protected $table = 'article';

    public function category()
    {
        return $this->belongsTo('ArticlesCategory', 'id_category', 'id');
    }
}

Model for categories:
class ArticlesCategory extends Model
{
    protected $table = 'article_category';

    public function articles()
    {
        return $this->hasMany('Articles', 'id_category', 'id');
    }
}

We get articles with categories in the controller In the template like this:
$article->category->name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question