John Davidson

php - Laravel : Combine two tables using Model relations

0 comments
Message:


i have two tables :: shops and attachments . Shops has all the details for shop and attachments with all the pictures for shop with ref_id as FK .


now for mobile app i have to list shops with Shop title and one image. I can achieve it using leftjoin as below.


Shop::select('shops.name as shop_name','attachments.name as picture')
->leftjoin('attachments','attachments.ref_id','=','shops.shop_id')
->paginate(10);

This returns just shop name and pictures ,
I want to achieve same results using relationships that i am not sure of how can i do that. Can someone please advise me on that


Edit


Shop Model


public function attachments(){
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}

dd(Shop::find(34)->attachments()->first());
dd(Shop::with('attachments')->get());

using first dd returns me attachment associated with 34 and but with query is not working and returns just shop



My Answer:
To achieve the same results using relationships in Laravel, you can define the relationship in your Shop model and then eager load the relationship when querying the shops. Here's how you can do it:

1. Define the relationship in your Shop model:

php
public function attachments(){
return $this->hasMany(Attachment::class, 'ref_id', 'shop_id');
}


2. Query the shops with the attachments relationship loaded:

php
$shops = Shop::with('attachments')->paginate(10);


This will load the attachments related to each shop and you can access them in your view like this:

php
@foreach($shops as $shop)

{{ $shop->shop_name }}


@if($shop->attachments->isNotEmpty())
Shop Image
@endif
@endforeach


This way, you can achieve the same result of listing shops with shop name and one image using relationships in Laravel.

Rate this post

4 of 5 based on 7893 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us