Answer the question
In order to leave comments, you need to log in
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;
}
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>
dd( $this->belongsToMany(
Category::class,
'category_image',
'image_id',
'category_id',
1
));
шина
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
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');
}
}
class ArticlesCategory extends Model
{
protected $table = 'article_category';
public function articles()
{
return $this->hasMany('Articles', 'id_category', 'id');
}
}
$article->category->name
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question