gibAlex
gibAlex

Reputation: 103

Laravel RelationShip (join with where)

I need help with Laravel 5 (using Eloquent)

I have 2 tables...

Model Driver drivers

Model DriverOnline drivers_online

I need to search for a result on (company=1 and driver_id=driver.id).

Please help me!

Upvotes: 0

Views: 20706

Answers (1)

Josh
Josh

Reputation: 3288

If you want to only fetch Driver based on a condition, you can just do this:

Driver::with('online')->where('company', 1)->get();

If the clause is on the relationship, use with and specify a query on that.

$company = 1;
$drivers = Driver::with(['online' => function($query) use ($company)
{
    $query->where('company', $company);
}]);

See "Eager Load Constraints":
https://laravel.com/docs/5.0/eloquent

Take note of my use. This allows you to include variables from the scope into your Closure instance.

And be aware, if you use either solution, you must set up a relationship. Consult the link I shared with more information on that.

Edit: As per our conversation.

$drivers = Driver::where('company_id','=',1)
    ->with('driversOnline')
    ->whereHas('driversOnline', function($query) {
        $query->where('online','=',1);
    })
    ->get();

Upvotes: 6

Related Questions