pkd
pkd

Reputation: 514

select data from 3 tables in laravel by using Eloquent ORM

I am new to laravel and stuck on getting data using Eloquent ORM.

My Scenario is I have 3 tables

  1. user - Contains user info
  2. location - Contains Location info
  3. location_user - Contains user id , location id , time when the user visited that location.

Now a user can visit a location multiple times and a location can be visited by multiple users.

I want to get all location name that a user visited on particular date.

But unable to get.

Below is the db structure

location_user table - id user_id location_id visitedtime

location table - id latitude longitude locality

user table - id name phone email

and In user model I have defined the relation

public function locations()
{
return $this->belongsToMany('Location')->withPivot('visitedtime');
}

when i use this function in controller then i get all the locations visited by that user

User::find(2)->locations()->select('locations.locality',locations.id')->get()

How can put condition on visitedtime on the above function

Upvotes: 1

Views: 726

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

User::find(2)
     ->locations()
     ->select('locations.locality',locations.id')
     ->where('pivot_visitedtime', $someDate)
     // or
     // ->where('location_user.visitedtime', $someDate)
     ->get()

// and for $someDate you can use Carbon bc it's stupid-simple, eg.:
$someDate = Carbon::parse('yesterday');

Upvotes: 1

Related Questions