Reputation: 131
I use many-to-many relation.
It is necessary to list the articles to which categories the post belongs, I did this with the help of the builder, since I do not know how to do this, via ORM.
I have three tables:
categories -id -name
images -id -image -description
category_image (pivot table) -id -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 article, there will be 2 more requests to the database, which is very bad.
output so
public function index()
{
$posts = Image::all();
return view('admin.posts.index', ['posts'=>$posts]);
}
I tried to get categories name with ->
@foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->description}}</td>
<td>{{$post->getCategoryTitle($post->id)}}</td>
<tr>
@endforeach
Image model
dd( $this->belongsToMany(
Category::class,
'category_image',
'image_id',
'category_id',
1
));
Is there any easy way to get category name for each image using relation.
Upvotes: 1
Views: 783
Reputation: 2901
in image model
public function categories(){
return $this->belongsToMany(Category::class)
}
in category model
public function images(){
return $this->belongsToMany(Image::class)
}
with()
for eager loading, provides you to get categories in single query
$posts = Image::with("categories")->get();
foreach($posts as $post) {
foreach ($post->categories as $category){
$category->name
}
}
Upvotes: 4
Reputation: 1797
If your relationships are set up correctly with laravel you can use the shorthand ->with('categories') (name dependin on the name of your belongs to many function in your class) to grab the category row as well
Upvotes: 1