garjoka madafa
garjoka madafa

Reputation: 3

Convert DB Join Query to Eloquent Relationship

I have the following functions in my User model:

public function getInterests()
{

    return $this->hasMany('App\Interest')->get();

}

public function getGifts()
{

    return DB::table('gifts')
        ->join('sent_gifts', function ($join) {
            $join->on('gifts.id', '=', 'sent_gifts.gift_id')
                ->where('user_2', $this->id);
        })
        ->join('users', function ($join) {
            $join->on('users.id', '=', 'sent_gifts.user_1');
        })
        ->get();

}

I couldn't understand how to create complex Eloquent Relationships, but I would like to use all of the benefits of Eloquent ORM, such as accessors and carbon instances on dates.

How would I go about converting my getGifts() function to an Eloquent Relationship?

P.S: I already have my App\User, App\Gift and App\SentGift models created.

Upvotes: 0

Views: 369

Answers (1)

Keval Mangukiya
Keval Mangukiya

Reputation: 2493

You can use like this. It is my relationship.

User Model

class User extends Eloquent { 
   protected $table = 'users'; 
   public function posts() { 
     return $this->hasMany('App\Post'); 
   } 
}

Post Model

class Post extends Eloquent { 
  protected $table = 'posts'; 
  public function comments() { 
    return $this->hasMany('App\Comment'); 
  } 
 }

And query use like following..

User::with('posts.comments')->get();

Upvotes: 0

Related Questions